zl程序教程

您现在的位置是:首页 >  其它

当前栏目

Unity 通过向量点乘叉乘判断方位

通过 判断 Unity 向量 方位
2023-06-13 09:11:38 时间

点积的计算方式为:a*b = |a| * |b| cos<a,b> 其中|a|和|b|表示向量的模,<a,b>表示两个向量的夹角。通过点积可以判断一个物体在另一个物体的前方还是后方。

using UnityEngine;

public class Foo : MonoBehaviour
{
    //创建两个物体A和B
    public Transform A;
    public Transform B;

    //点积结果
    private float dot;

    private void Update()
    {
        //物体A到B的方向
        Vector3 direction = B.position - A.position;
        //点积运算
        dot = Vector3.Dot(direction.normalized, A.forward);
    }

    private void OnGUI()
    {
        //点积结果大于0表示物体B在物体A的前方 否则在后方
        GUILayout.Label($"B在A的{(dot > 0 ? "前方" : "后方")}", "Box");
    }
}

叉积的性质:

1.c垂直于a,c垂直于b,即向量c垂直于向量a、b所在的平面

2.模长|c| = |a| * |b| sin<a,b>

3.满足右手法则。a * b != b * a 而 a * b = - b * a

可以使用叉积来判断一个物体在另一个物体的左方还是右方。

using UnityEngine;

public class Foo : MonoBehaviour
{
    public Transform A;
    public Transform B;
    //叉乘结果
    private Vector3 cross;

    private void Update()
    {
        //物体A到B的方向
        Vector3 direction = B.position - A.position;
        //叉积运算
        cross = Vector3.Cross(direction.normalized, A.forward);
    }

    private void OnGUI()
    {
        //大于0表示B在A的左方,否则为右方
        GUILayout.Label($"B在A的{(cross.y > 0 ? "左方" : "右方")}", "Box");
    }
}