Sign in to follow this  

pong collision detection

Recommended Posts

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;
return true;

Hope this helps.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this