Home > Mobile >  Unity: Finding Side that a 2D Collision Occurs On
Unity: Finding Side that a 2D Collision Occurs On

Time:01-31

I am working on a 2D Game. I am detecting when an object collides with the player, but I am getting a little stuck trying to find which side it is colliding on. I want to be able to rotate the player to face either Left, Right, Up, or Down towards the object it collided with. How can I find which side the object collided on so that I can then rotate the player accordingly?

I am using a Rigidbody2D on the player and 2D Colliders, I am able to find the point that it collides with the player using Collider2D.ClosestPoint() but am unsure how to proceed. Thank you for the help.

CodePudding user response:

the most simple solution I see is that you first get the size of the player 2D collider with BoxCollider2D.size. Then you create a simple block of if statements to check on which side is the hit point based on the player position.

Something like this should work:

var size = collider.size;
var hitPoint = collider.ClosestPoint();
var playerPosition = transform.position;

if (hitPoint.x >= playerPosition   size.x/2)
   // hit on the right
else if (hitPoint.y >= playerPosition   size.y/2)
   // hit on the top
else if (hitPoint.x <= playerPosition - size.x/2)
   // hit on the left
else if (hitPoint.y <= playerPosition - size.y/2)
   // hit on the bottom

Note that there may be some problems in the edge cases. You reorder the if statements based on your wanted behaviour. Hope this help.

CodePudding user response:

So once you have the hit point

var hitPoint = collider.ClosestPoint();
// Instead of the transform.position the collider.bounds.center is often more accurate 
var playerPosition = collider.bounds.center;

You could e.g. take the direction between those and check where it hits relative to the player like e.g.

var dir = hitPoint - playerPosition;
var angle = Vector2.SignedAngle(transform.right, dir);

// Now check the angle
if(Maths.Abs(angle) <= 45)
{
    Debug.Log("hit right");
}
else if(angle > 45 && angle <= 135)
{
    Debug.Log("hit top");
}
else if(angle < 45 && angle >= -135)
{
    Debug.Log("hit bottom");
}
else
{ 
    Debug.Log("hit left");
}
  • Related