首页 > 解决方案 > Unity3d:找到哪个游戏对象在前面

问题描述

我有两个gameObjects AB。他们rotated90 degrees,这使它的local y axis脸向前。

第一种情况

在此处输入图像描述

在这种情况下,local y position of B领先于local y position of A

第二种情况

在此处输入图像描述

尽管它们的全局位置与第一种情况相同,但我们可以在这里观察到local y position of A领先于local y position of B.

我尝试使用A.transform.localPosition.yandB.transform.localPosition.y来查找哪个更大,但它不起作用。在这两种不同的情况下,我该怎么做才能找到哪个是最前面的?

标签: unity3dmathvectorposition

解决方案


您可以比较Vector3.Dot(A.position, A.forward)Vector3.Dot(B.position, B.forward)找到与他们的前锋相关的前锋。
具有较大点积的对象在前面,这适用于所有旋转,包括 3D 旋转。

您可以使用以下代码段自行测试:

// Assign these values on the Inspector
public Transform a, b;
public float RotationZ;

void Update() {
    a.eulerAngles = new Vector3(0, 0, RotationZ);
    b.eulerAngles = new Vector3(0, 0, RotationZ);

    Debug.DrawRay(a.position, a.right, Color.green);
    Debug.DrawRay(b.position, b.right, Color.red);

    var DotA = Vector2.Dot(a.position, a.right);
    var DotB = Vector2.Dot(b.position, b.right);

    if (DotA > DotB) { Debug.Log("A is in front"); }
    else { Debug.Log("B is in front"); }
}

推荐阅读