Jump to content
  • Advertisement
Sign in to follow this  
phil67rpg

pong collision detection

This topic is 4369 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!