Unity向量点乘的一些基础点

下边关于一些Unity向量点乘的基础点呢

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DotScript : MonoBehaviour
{
    
    
    public Transform target;
    // Start is called before the first frame update
    void Start()
    {
    
    
        //点乘的几何意义
        //在自己向量上投影的长度
        //点乘结果>0 两个向量夹角为锐角
        //点乘结果=0两个向量为直角
        //点乘结果<0两个向量夹角为钝角
        //我们可以用这个规律判断地方的大致方位
        
    }

    // Update is called once per frame
    void Update()
    {
    
    
        画线段 前两个参数分别是起点和终点
        //Debug.DrawLine(this.transform.position, this.transform.position + this.transform.forward, Color.red);
        /画射线 前两个参数是起点和方向
        //Debug.DrawRay(this.transform.position, this.transform.forward, Color.white);
        //步骤
        //1.用单位向量算出点乘结果
        float dotResult = Vector3.Dot(this.transform.forward, (target.position - this.transform.position).normalized);
        //2用反三角函数得出角度
        // print("角度" + Mathf.Acos(dotResult) * Mathf.Rad2Deg);
        if (dotResult >= 0)
        {
    
    
            Debug.Log("他在我前方");
        }
        else
        {
    
    
            Debug.Log("他在我后方");
        }

        float dotResultg = Vector3.Dot(this.transform.forward, (target.position - this.transform.position).normalized);

        print("角度1:" + Mathf.Acos(dotResult) * Mathf.Rad2Deg);

        print("角度2:" + Vector3.Angle(this.transform.forward, target.position - this.transform.position));
        
    }
}

发现一些敌人入侵的脚本

public class FindEnemy : MonoBehaviour
{
    
    
    public Transform B;
    // Start is called before the first frame update
    void Start()
    {
    
    
        
    }

    // Update is called once per frame
    void Update()
    {
    
    
        //if(Vector3.Distance(this.transform.position,B.transform.position)<=5)
        //{
    
    
        //    //第一步 算出点乘结果(方向向量)
        //    float dotResult = Vector3.Dot(this.transform.forward, (B.transform.position - this.transform.position).normalized);
        //    //第二步 通过反余弦函数 算出夹角
        //    if(Mathf.Acos(dotResult)*Mathf.Rad2Deg<=22.5f)
        //    {
    
    
        //        Debug.Log("发现入侵者");
                  
        //    }
        //}

        if(Vector3.Distance(this.transform.position,B.transform.position)<=5&& Vector3.Angle(this.transform.forward,B.transform.position-this.transform.position)<=22.5f)
        {
    
    
            Debug.Log("发现入侵者");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/charlsdm/article/details/127071032