2d Collision detection

in my new project i want to detect when a ball hits a rectangle. every article/tutorial i have red about this has involved sprites which gets me a little confused. my program has no sprites. my question to you is, can you please explain how this 2d collision would be detected. if it makes any difference im using opengl.
closed account (oz10RXSz)
Use this to calculate distance from the center of the ball to each of the four edges of the rectangle. http://www.intmath.com/Plane-analytic-geometry/Perpendicular-distance-point-line.php
Last edited on
If your rectangle's edges are aligned to the axes, there is a faster way.
1
2
3
4
5
int target_x = ball_x, target_y = ball_y;
if(target_x < rect_left) target_x = rect_left;
if(target_x > rect_right) target_x = rect_right;
if(target_y < rect_botom) target_y = rect_botom;
if(target_y > rect_top) target_y = rect_top;

Now target is the point in the rect, nearest to the ball. If the distance between target and ball is less than radius, that means collision.

If your rect is not aligned to axes, you could first rotate it (and the ball too) and then do the same, but then, I'm not sure that it would be faster or more simple than what xoreaxeax suggested.
Topic archived. No new replies allowed.