Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting the Direction of a Collision

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.

like image 972
slifty Avatar asked Feb 21 '11 05:02

slifty


People also ask

How do you do collision detection?

If both the horizontal and vertical edges overlap we have a collision. We check if the right side of the first object is greater than the left side of the second object and if the second object's right side is greater than the first object's left side; similarly for the vertical axis.

How can you determine of there is a collision between two circles?

Checking collision between two circles is easy. All you have to do is check whether the distance between the center of each circle is less than the sum of their radii (radii is the plural for radius). For box/circle collision, you have to find the point on the collision box that is closest to the center of the circle.

What do we call the process of determining if any two sprites have collided with each other?

Sometimes, you'll want to know when two sprites are touching each other. Game Lab uses the method isTouching to check whether one sprite is touching another sprite (the target).


1 Answers

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

like image 121
Photonic Avatar answered Oct 29 '22 04:10

Photonic