Vector3.Cross

上期介绍了Vector.Dot可以用来判断敌人处于自身的前方or后方,那么这期就是通过叉乘来判断敌人处于自身的左方or右方

Vector3.Cross_第1张图片

public class CrossTest : MonoBehaviour
{
    public GameObject sphere;
    public GameObject cube;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    private void Update() {
        var v=sphere.transform.position-cube.transform.position;
        Vector3 cross=Vector3.Cross(cube.transform.forward,v);

        Debug.DrawLine(cube.transform.position,cube.transform.forward*10,Color.red);
        Debug.DrawLine(cube.transform.position,sphere.transform.position,Color.green);
        Debug.DrawRay(cube.transform.position,cross,Color.blue);
    }

}

Vector3.Cross_第2张图片 

 可以看到,敌人位于自身右边时(x轴正方向)根据右手定则,叉乘的结果方向向上

将球移动至自身右边时

Vector3.Cross_第3张图片

 根据这个特性,我们可以根据叉乘结果的正负来判断敌人位于自身的左边or右边。

public class CrossTest : MonoBehaviour
{
    public GameObject sphere;
    public GameObject cube;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    private void Update() {
        var v=sphere.transform.position-cube.transform.position;
        Vector3 cross=Vector3.Cross(cube.transform.forward,v);

        Debug.DrawLine(cube.transform.position,cube.transform.forward*10,Color.red);
        Debug.DrawLine(cube.transform.position,sphere.transform.position,Color.green);
        Debug.DrawRay(cube.transform.position,cross,Color.blue);

        if(cross.y>0)
        {
            Debug.Log("在右边");
        }else{Debug.Log("在左边");}
    }

}

你可能感兴趣的:(unity基础,unity)