# Checking for collision of two rectangles using intersect

• 12-08-2010, 06:05 AM
Boatski
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:
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?
• 12-09-2010, 05:53 AM
Maxideon
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

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).
• 12-09-2010, 02:40 PM
Boatski
I found a solution a few hours before you posted, but I will give yours a shot because it looks a bit cleaner.

Thanks