I took a lot of time, to find a good way of detecting collision in one of my games (it was more of a learning experience, just to mess around with SDL)
however, simple bounding box collision isn't hard to do at all.
To make simple collison with a single box, it's as easy as checking whether the boxes points have crossed or passed the obstacles. All you have to do is check is the players proximity to the object
A good simple collision tutorial can be found on Lazyfoo.net here
http://lazyfoo.net/SDL_tutorials/lesson17/index.php
EDIT: I wrote this really long post, but it was probably a little confusing, as I realised you're not using SDL, so your function will look a little different (should you choose to use a function), to make the link relevant, you could consider declaring a struct or class (struct seemed like the cleanest one to do at the time) to make your PlayerX,PlayerY etc into Player.x,Player.y etc
Code: Select all
typdef struct rect{
int x;
int y;
int w;
int h;
};
rect Player
rect Obstacle
now, instead of using SDL Rects as arguments, you can simply pass your own types
Code: Select all
bool Check_Collision(rect Player, rect Obstacle) // this is the collision function in the lazyfoo tutorial, but with user defined //rects as arguments instead of SDL_Rects
bool check_collision( rect A, rect B ) {
//The sides of the rectangles
int leftA, leftB; int rightA, rightB;
int topA, topB; int bottomA, bottomB;
//Calculate the sides of rect A
leftA = A.x;
rightA = A.x + A.w;
topA = A.y;
bottomA = A.y + A.h;
//Calculate the sides of rect B
leftB = B.x;
rightB = B.x + B.w;
topB = B.y;
bottomB = B.y + B.h;
//If any of the sides from A are outside of B
if( bottomA <= topB )
{
return false;
}
if( topA >= bottomB )
{
return false;
}
if( rightA <= leftB )
{
return false;
}
if( leftA >= rightB )
{
return false;
}
//If none of the sides from A are outside B return true;
}
Now if you want to test for collision for one of your objects, you simply call the function, and it will return true or false, depending on the presence of a collison, if there is one, you can tell your player to move back.
Code: Select all
if(Check_Collision(Player,Obstacle))
{
// Move player back, whichever way you choose to do it
}
I hope this helped anyway with working out a way to do collision in a simpler way
PS: no credit taken for the code, I found this out from lazyfoo originally, all i've done is change the function so that it accepts user defined rects instead of SDL_Rects
---------------------------------------------------------------------------------------
I think I can program pretty well, it's my compiler that needs convincing!
---------------------------------------------------------------------------------------
And now a joke to lighten to mood :D
I wander what programming language anakin skywalker used to program C3-PO's AI back on tatooine? my guess is Jawa :P