Results 1 to 3 of 3
  1. #1
    Boatski is offline Member
    Join Date
    Dec 2010
    Posts
    3
    Rep Power
    0

    Default Solved: Checking for collision of two rectangles using intersect

    I'm trying to make a pong game. I've got a basic working example. I'm using intersects to check and see if the ball (a rectangle) intersects the right bumper (another rectangle). If they do intersect, then the ball should go the other way.

    Here's the statement I'm using to check for intersection:
    Java Code:
    		if (ball.intersects(rightBumper) == true) {
    			dx *= -1;
    		}
    Once the ball does intersect the right bumper it will go the other way by multiplying dx by -1. The problem is dx is then constantly multiplied by -1 for some reason and just bounces back and forth by 5 pixels. I can't seem to figure out why intersects keeps returning true even if the ball doesn't intersect the bumper.

    I've also tried using hit from Graphics2D, but I get the same result.

    Can anyone point me in the right direction?
    Last edited by Boatski; 12-09-2010 at 02:39 PM. Reason: Solved

  2. #2
    Maxideon is offline Member
    Join Date
    Jun 2010
    Posts
    28
    Rep Power
    0

    Default

    There's a disconnect between your x and y variables and when the ball is actually updated to these values.

    Basically, just delete those variables and replace all the x's with box.x and all the y's with box.y. Also delete this statement in paintComponent

    Java Code:
    //Moves the ball around
    ball.setRect(x, y, 25, 25);
    The ball will be moved in the actionPerformed method instead (when you change the x's and y's to box.x and box.y).

  3. #3
    Boatski is offline Member
    Join Date
    Dec 2010
    Posts
    3
    Rep Power
    0

    Default

    I found a solution a few hours before you posted, but I will give yours a shot because it looks a bit cleaner.

    Thanks

Similar Threads

  1. Why only one of the two rectangles is painted?
    By JOHNINALBANY in forum Java 2D
    Replies: 5
    Last Post: 07-07-2012, 11:54 PM
  2. Collision between 2 rectangles
    By CNew in forum New To Java
    Replies: 1
    Last Post: 12-05-2010, 05:18 AM
  3. Rectangles method
    By bdario1 in forum New To Java
    Replies: 31
    Last Post: 03-31-2010, 10:32 PM
  4. Area Intersect
    By Java Tip in forum java.awt
    Replies: 0
    Last Post: 06-23-2008, 12:07 AM
  5. Replies: 0
    Last Post: 06-23-2008, 12:06 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •