i’m having some problems with collission in a small 2D game i’m writing. I’m currently working on a function that i want to find if the player character collides with a block, and which side of the block he collided with.
Currently i have something like (psuedo-code):
if(PLAYER_BOX IS WITHIN THE BLOCKS Y_RANGE)
{
if(PLAYER_BOX_RIGHT_SIDE >= BLOCK_LEFT_SIDE && PLAYER_BOX_RIGHT_SIDE <= BLOCK_RIGHT_SIDE)
{
return LEFT;
}
else if(PLAYER_LEFT_SIDE <= BLOCK_RIGHT_SIDE && PLAYER_LEFT_SIDE >= BLOCK_LEFT_SIDE)
{
return RIGHT;
}
}
else if(PLAYER_BOX IS WITHIN BLOCK X_RANGE)
{
if(PLAYER_BOTTOM_SIDE >= BLOCK_TOP_SIDE && PLAYER_BOTTOM_SIDE <= BLOCK_BOTTOM_SIDE)
{
return ABOVE;
}
else if(PLAYER_TOP_SIDE <= BLOCK_BOTTOM_SIDE && PLAYER_TOP_SIDE >= BLOCK_TOP_SIDE)
{
return BELOW;
}
}
Do i have some logic error here? Or have i simply wrote something wrong in my code?
ABOVE collision works, but it doesn’t recognize sideways collission when it should, and sometimes it does when it should’nt.
The game is a SuperMario clone, so it’s a sidescroller 2D platformer.
I’m guessing the issue is direction.
What you really want to do is to take into account the “player” direction first and then do your checks.
If you don’t know what direction the player is moving in you could get a number for false hits depending on how “fast” your sprites are moving.
For example if you have movement directions (up down left right) then your code might look like this: