Detecting the Direction of a Collision

slifty picture slifty · Feb 21, 2011 · Viewed 11.5k times · Source

A square tile collides with another square tile. The bartender says...

I have:

  • The height, width, x, and y of both tiles.
  • The 2D vector of the movement which caused the collision.

I need to know from what SIDE the collision occurred (e.g. top, bottom, left, right) in order to reset the location appropriately.

I will give a mental cookie to whoever can answer this question, because I've been trying for too many hours and this seems fundamental.

Answer

Photonic picture Photonic · Nov 12, 2012
float player_bottom = player.get_y() + player.get_height();
float tiles_bottom = tiles.get_y() + tiles.get_height();
float player_right = player.get_x() + player.get_width();
float tiles_right = tiles.get_x() + tiles.get_width();

float b_collision = tiles_bottom - player.get_y();
float t_collision = player_bottom - tiles.get_y();
float l_collision = player_right - tiles.get_x();
float r_collision = tiles_right - player.get_x();

if (t_collision < b_collision && t_collision < l_collision && t_collision < r_collision )
{                           
//Top collision
}
if (b_collision < t_collision && b_collision < l_collision && b_collision < r_collision)                        
{
//bottom collision
}
if (l_collision < r_collision && l_collision < t_collision && l_collision < b_collision)
{
//Left collision
}
if (r_collision < l_collision && r_collision < t_collision && r_collision < b_collision )
{
//Right collision
}

This doesn't solve when object is inside one of the other. But it does work with overlapping