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

3
在Unity3d中,我可以使用hit.normal获取与碰撞器发生碰撞的表面法线,但是有没有一种方法可以找到被击中的哪一侧,这是Unity3d提供的内容?一种解决方案是查看法线的方向,对于静态对象应该有效,但是对于方向会改变的动态和移动对象呢?
3个回答

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

3
InverseTransformPoint 接受一个 Vector3 参数,而不是 ContactPoint[]。参考链接:http://docs.unity3d.com/ScriptReference/Transform.InverseTransformPoint.html - Silvio Guedes

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");
        }
    }
}

-1

这个有效:

function OnCollisionEnter(collision: Collision) {
    var relativePosition = transform.InverseTransformPoint(collision.transform.position);

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接