如何找到撞击器的哪一侧被击中hit.normal?

时间:2011-09-16 15:47:26

标签: collision-detection unity3d game-physics

在Unity3d中,我可以使用hit.normal来获得碰撞器碰撞的表面的法线,但是有没有办法找到哪一侧被击中了Unity3d提供的?

一种解决方案是查看法线的方向,并且应该适用于静态对象但是方向发生变化的动态和移动对象呢?

3 个答案:

答案 0 :(得分:4)

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.”);
    }
}

答案 1 :(得分:0)

void OnCollisionEnter(Collision collision)
{            
    Vector3 dir = (collision.gameObject.transform.position - gameObject.transform.position).normalized;

    if(Mathf.Abs(dir.z) < 0.05f)
    {
        if (dir.x > 0)
        {
            print ("RIGHT");    
        }
        else if (dir.x < 0)
        {
            print ("LEFT");             
        }
    }
    else
    {
        if(dir.z > 0)
        {
            print ("FRONT");
        }
        else if(dir.z < 0)
        {
            print ("BACK");
        }
    }
}

答案 2 :(得分:0)

这有效:

map()