Code: Select all
int IsCollision(SDL_Rect *r1, SDL_Rect *r2)
{
if (r1->x + r1->w < r2->x ||
r1->x > r2->x + r2->w ||
r1->y + r1->h < r2->y ||
r1->y > r2->y + r2->h)
return 0;
else
return 1;
}
Why?
Say we have 2 objects, square and ball.
Square is stationary, ball is moving at 5 pixels per frame (60 frames per second).
Using the above collision detection code, we can move ball 5 pixels in whatever direction each frame and then check if there was a collision. If there was, we just reverse the x (and/or) y velocities of the ball and move it back that many pixels.
The problem with that is, unless the ball collides perfectly 5 pixels inside the square, then when we move it back those 5 pixels, it won't be directly on the edge of the square but some pixels off.
This would be horrible in a platform game or any game in general really, because it's not precise.
As lazy foo stated, the better way of going about this would be to check:
"If there is a collision, move object 2 to the outskirts of object 1 on the side in which object 2 collided."
For instance, if the ball hit the square from the right side of the square, move the balls x coordinate to the squares x coordinate plus the squares width (assuming the x, y native point for the square was the top left corner, which in my case it is).
-----
So sorry for the long drawn out explanation. I just wanted everyone to be on the same page as me.
I can't use precise detection if I don't know which side the collision occured from.
I searched these forums and found a post Falco made not to long ago about separating axis theorem which I haven't gotten into yet. I wasn't able to get that code to work properly with my game for some reason. Even so, that only checks if the collision was x or y which checks the left, right, and up, down sides. I need to check from all 4 sides since I'm using square-based objects.
-----
If anyone knows of a better way of doing this, please let me know.