# pong collision detection

## Recommended Posts

well I am using opengl and c++ to make a pong game, I have the ball and paddles, but need to detect for collisions when the ball hits the paddles,I need something very simple

##### Share on other sites
Assuming that you’re using non-rotated rectangles for your collision detection, there is a very simple algorithm for doing this.

Assume your rectangles are defined like so:

struct Rect {	float x, y; //upper-left corner of rectangle	float w, h; //width and height of rectangle}

Then there are only 4 cases when Rect1 does not collide with Rect2 (you might want to draw these out):

1. The right side of Rect1 is to the left of the left side of Rect2
2. The left side of Rect1 is to the right of the right side of Rect2.
3. The bottom of Rect1 is above the top of Rect2.
4. The top of Rect1 is below the bottom of Rect2.

That being said, let’s look at the comparisons needed to determine each case:

1. The right side of Rect1 is at Rect1.x + Rect1.w, and the left side of Rect2 is at Rect2.x. So check to see if ((Rect1.x + Rect1.w) < Rect2.x).

2. The left side of Rect1 is at Rect1.x, and the right side of Rect2 is at Rect2.x + Rect2.w. So check (Rect1.x > (Rect2.x + Rect2.w)).

3. The bottom fo Rect1 is at Rect1.y + Rect1.h, and the top of Rect2 is at Rect2.y. So check ((Rect1.y + Rect1.h) < Rect2.y).

4. The top of Rect1 is at Rect1.y, and the bottom of Rect2 is at Rect2.y + Rect2.h. So check (Rect1.y > (Rect2.y + Rect2.h)).

If any of the above four are true, then there is no collision, otherwise there is. So to combine it all together, do:

if (((Rect1.x + Rect1.w) < Rect2.x) || (Rect1.x > (Rect2.x + Rect2.w)) || ((Rect1.y + Rect1.h) < Rect2.y) || (Rect1.y > (Rect2.y + Rect2.h)))	return false;else	return true;

Hope this helps.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628333
• Total Posts
2982126

• 24
• 9
• 9
• 13
• 11