Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7574407
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T16:25:45+00:00 2026-05-30T16:25:45+00:00

I’ve just started Java and we have been asked to produce pong (or a

  • 0

I’ve just started Java and we have been asked to produce pong (or a twist on it). I am currently working on the collision between the ball and the players bat. I’ve got this code.

Rectangle2D.Double player;
Ellipse2D.Double ball;
public void drawActualPicture( Graphics2D g )
{
    // Players Bat

    g.setPaint( Color.green );              // Paint Colour
    player = new Rectangle2D.Double( playerX, playerY, PW, PH );
    g.fill(player);

    // The ball at the current x, y position (width, height)
    g.setPaint( Color.red );
    ball = new Ellipse2D.Double( x-HALF_BALL_SIZE, y-HALF_BALL_SIZE, BALL_SIZE, BALL_SIZE );
    g.fill( ball );
}

Some irrelevant code has been removed.

Then to detect my collision I’ve used

if ( ball.getBounds2D() == player.getBounds2D() )
{
    System.out.println("true");
    //x_inc = -1*ballS;
}

When the code is used the game simple freezes. When commented out the game runs fine.

Any ideas? Am I using the correct method in the correct way? Would it be better to use intersects?

Thanks

EDIT: It appears that anything involving .getBounds2D(); causes the game to crash. Any ideas?

EDIT2: Adding all of code-completly not needed parts

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;
import javax.swing.JFrame;
import javax.swing.JPanel;

/*
 * Note If you change S (Speed) collision detection will be more complex
 *      as the ball edge may be within the bat.
 *      Ignores concurrency issues (x,y access)
 */

class Main
{
    public static void main( String args[] ) //
    {                                        //
        System.out.println("Application");
        Application app = new Application();
        app.setVisible(true);
        app.run();
    }                                        //
}

class Application extends JFrame            // So graphical
{
    private static final int H = 600;         // Height of window
    private static final int W = 800;         // Width  of window

    public Application()
    {
        setSize( W, H );                        // Size of application
        addKeyListener( new Transaction() );    // Called when key press
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public void update( Graphics g )          // Called by repaint
    {                                         //
        drawPicture( (Graphics2D) g );          // Draw Picture
    }

    public void paint( Graphics g )           // When 'Window' is first
    {                                         //  shown or damaged
        drawPicture( (Graphics2D) g );          // Draw Picture
    }

    private Dimension     theAD;              // Alternate Dimension
    private BufferedImage theAI;              // Alternate Image
    private Graphics2D    theAG;              // Alternate Graphics

    public void drawPicture( Graphics2D g )   // Double buffer
    {                                         //  allow re-size
        Dimension d    = getSize();             // Size of curr. image

        if (  ( theAG == null )  ||
        ( d.width  != theAD.width ) ||
        ( d.height != theAD.height ) )
        {                                       // New size
            theAD = d;
            theAI = (BufferedImage) createImage( d.width, d.height );
            theAG = theAI.createGraphics();
            AffineTransform at = new AffineTransform();
            at.setToIdentity();
            at.scale( ((double)d.width)/W, ((double)d.height)/H );
            theAG.transform(at);
        }

        drawActualPicture( theAG );             // Draw Actual Picture
        g.drawImage( theAI, 0, 0, this );       //  Display on screen
    }

    // The ball position and how to increment to next position
    private int x = W/2, x_inc = 1;
    private int y = H/2, y_inc = 1;

    // The bat position and how to increment to next position
    private int playerX = 60;
    private int playerY = PH/2, playerY_inc = 1;

    double count = 0.00;

    // Called on key press 

    class Transaction implements KeyListener  // When character typed
    {
        public void keyPressed(KeyEvent e)      // Obey this method
        {
            // Key typed includes specials
            switch ( e.getKeyCode() )              // Character is
            {
                /*
                case KeyEvent.VK_LEFT:               // Left Arrow
                x_inc = -1;
                break;
                case KeyEvent.VK_RIGHT:              // Right arrow
                x_inc = 1;
                break;
                 */
                case KeyEvent.VK_UP:                 // Up arrow
                playerY_inc = -1;
                break;
                case KeyEvent.VK_DOWN:               // Down arrow
                playerY_inc = 1;
                break;
            }
            // x,y could send to a server instead of calling 
            repaint();                            // Call update method
        }

        public void keyReleased(KeyEvent e)
        {
            switch ( e.getKeyCode() )              // Character is
            {  
                /*
                case KeyEvent.VK_UP:                 // Up arrow
                playerY_inc = playerY_inc;
                break;
                case KeyEvent.VK_DOWN:               // Down arrow
                playerY_inc = playerY_inc;
                break;
                 */
            }
        }

        public void keyTyped(KeyEvent e)
        {
            // Normal key typed
            char c = e.getKeyChar();              // Typed
            repaint();                            // Redraw screen
        }
    }

    private static final int B = 6;           // Border offset
    private static final int M = 26;          // Menu offset
    private static final int BALL_SIZE = 10;  // Ball diameter
    private static final int HALF_BALL_SIZE = BALL_SIZE/2;

    //Players Bat
    private static final int PW = 20;
    private static final int PH = 100;
    private static final int HALF_PLAYER = PH/2;

    // Code called to draw the current state of the game
    Rectangle2D.Double player;
    Ellipse2D.Double ball;
    public void drawActualPicture( Graphics2D g )
    {
        // White background
        g.setPaint( Color.white );
        g.fill( new Rectangle2D.Double( 0, 0, W, H ) );

        Font font = new Font("Monospaced",Font.PLAIN,24); 
        g.setFont( font ); 

        // Blue playing border
        g.setPaint( Color.blue );              // Paint Colour
        g.draw( new Rectangle2D.Double( B, M, W-B*2, H-M-B ) );

        // Players Bat

        g.setPaint( Color.green );              // Paint Colour
        player = new Rectangle2D.Double( playerX, playerY, PW, PH );
        g.fill(player);

        // Display state of game
        g.setPaint( Color.blue );
        FontMetrics fm = getFontMetrics( font );

        String fmt = "Score/ Time lasted = %3f";
        String text = String.format( fmt, count );
        g.drawString( text, W/2-fm.stringWidth(text)/2, M*2 );

        // The ball at the current x, y position (width, height)
        g.setPaint( Color.red );
        ball = new Ellipse2D.Double( x-HALF_BALL_SIZE, y-HALF_BALL_SIZE, BALL_SIZE, BALL_SIZE );
        g.fill( ball );
    }

    // Main program loop

    public void run()
    {
        int ballS = 1;                    // Speed 1 - 5
        int playerS = 1;
        try
        {
            while ( true )
            {
                count = count + 0.015;
                //Ball hitting walls
                //Right wall
                if ( x >= W-B-HALF_BALL_SIZE )
                {
                    x_inc = -1*ballS;
                }
                //Left wall
                if ( x <= 0+B+HALF_BALL_SIZE )
                {
                    count = count;
                    break;
                }
                //Bottom Wall
                if ( y >= H-B-HALF_BALL_SIZE )
                {
                    y_inc = -1*ballS;
                }
                //Top Wall
                if ( y <= 0+M+HALF_BALL_SIZE )
                {
                    y_inc = 1*ballS;
                }
                //Player Hiting Wall
                //Bottom Wall
                if ( playerY >= H-B-100 )
                {
                    playerY_inc = -1*playerS;
                }
                //Top Wall
                if ( playerY <= 0+M )
                {
                    playerY_inc = 1*playerS;
                }
                //Player
                Rectangle2D ballB = ball.getBounds2D();

                if ( ball.getBounds2D().intersects(player.getBounds2D() ))
                {
                    System.out.println("true");
                    //x_inc = -1*ballS;
                }

                //Wall

                x += x_inc;
                y += y_inc;

                playerY += playerY_inc;

                repaint();                      // Now display

                Thread.sleep( 10 );             // 100 Hz
            }
        } catch ( Exception e ) {};
    }
}

Edit: Solved it, I used math and x-y coords to work out if it was inside the other shape. Thanks the help.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T16:25:46+00:00Added an answer on May 30, 2026 at 4:25 pm
     ball.getBounds2D() == player.getBounds2D()
    

    Is a reference check as they are objects; not primitives. You are checking if the Rectangle2D returned by both the game objects are one in the same (which they aren’t).

    To check if a Rectangle2D object intersects another Rectangle2D object you should do:

    ball.getBounds2D().intersects(player.getBounds2D())
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
I have a jquery bug and I've been looking for hours now, I can't
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have thousands of HTML files to process using Groovy/Java and I need to
link Im having trouble converting the html entites into html characters, (&# 8217;) i
this is what i have right now Drawing an RSS feed into the php,
I have this code to decode numeric html entities to the UTF8 equivalent character.
I want use html5's new tag to play a wav file (currently only supported
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.