Search code examples
collision-detectionunity-game-enginegame-physics

How to find which side of a collider has been hit from hit.normal?


In Unity3d, i can get the normal of the surface with which the collider collides using hit.normal, but is there a way to find which side has been hit what is provided bu Unity3d?

One solution is to see the orientation of the normal, and should work well for static objects but what about dynamic and moving objects whose orientation changes?


Solution

  • function OnCollisionEnter(collision : Collision)
    {
        var relativePosition = transform.InverseTransformPoint(collision.contacts);
    
        if(relativePosition.x > 0) 
        {
            print(“The object is to the right”);
        } 
        else 
        {
            print(“The object is to the left”);
        }
    
        if(relativePosition.y > 0) 
        {
            print(“The object is above.”);
        } 
        else 
        {
            print(“The object is below.”);
        }
    
        if(relativePosition.z > 0) 
        {
            print(“The object is in front.”);
        } 
        else 
        {
            print(“The object is behind.”);
        }
    }