2D Box Collision
Theory
If the corner of one square is inside the other square the
collision has occurred. For easier reading write 4 functions which check for
possible collision on each side (left, right, top, bottom). Then write another
function that compares which sides have a possible collision to figure out if
collision has actually occurred.
Example
Write a function that checks collision with a single side.
Note: sprite is 30 pixels large and getX and getY return the origin point of
the sprite which in this case is the top left corner.
bool Blue::possibleCollisionLeft(Orange* orange)
{
//get necessary coordinates
int blueLeftSide = getX();
int orangeLeftSide = orange->getX();
int orangeRightSide = orange->getX() + 30;
//return true if collision could occur on left side
if((blueLeftSide <=
orangeRightSide) && (blueLeftSide >= orangeLeftSide))
{
return true;
}
else
{
return false;
}
}
Write a function like
this for all 4 sides.
Then bring them all together in another function to compare
which ones return true. And don't forget to check if its even colliding with the object you want. If its not then return true, doing this at the beginning of the function will stop the function comparing all the edge functions for no reason.
bool Blue::orangeCollision(Orange* orange)
{
if(!orange)
{
return false;
}
if(!orange)
{
return false;
}
//compare collision function results, return true if a collision
has occured
if((possibleCollisionRight(orange)
== true && possibleCollisionBottom(orange)
== true)
|| (possibleCollisionLeft(orange) == true && possibleCollisionBottom(orange) == true)
|| (possibleCollisionLeft(orange) == true && possibleCollisionTop(orange) == true)
|| (possibleCollisionRight(orange) == true && possibleCollisionTop(orange) == true))
{
return true;
}
else
{
return false;
}
}
No comments:
Post a Comment