Search code examples
graphics2dcollision-detection

2D Collision (returns collided side)


Mario plays multiple games. Normally, while playing in a game, when he jumps [underneath] a question block, he gets a free surprise. When he encounters a Goomba or another dangerous hooligan, he simply jumps on its head. After coming to a different game, Mario jumps under a question box as usual and finds that nothing happens. Mario jumps on top of a Goomba and dies. Mario is very confused, what is wrong here?

This new game has collision detection (hence the death from the Goomba) but doesn't know how to tell which side has been collided with. Assuming only one side can collide at a time, and that the left of Mario can only collide with the right side of an object (right->left; top->bottom; etc.).

How can I do collision testing that also returns which side of poor Mario collided (to ensure jumping [underneath] a box gives him a surprise but jumping [on] a box doesn't give him anything).

Pseudo-code would be appreciated.


Solution

  • You could use current velocity, if your engine/game doesn't have lag issues.

    For instance:

    • touching box: if vertical speed isn't 'positive', no gift
    • touching foe: if vertical speed isn't 'negative', death

    I'm using vertical axis as usual in geometry, up toward the top of the screen, not usual in screen space where pixels starts at the top, so up is going down.