Unity 中通过向量点成可以计算出cos<夹角>=DOT(A,B);
但是Mathf.Acos(点乘后的结果) 得出的是把余弦值转换成弧度
我们需要除以Mathf.Deg2Rad 才可以转换成角度!
//拿到一个物体的前方向量
Vector3 RoleForwardV = MainRole.transform.forward;
//计算另一个物体与当前物体连线方向向量
Vector3 RoleToMonsterV = Monster.transform.position - MainRole.transform.position;
//点乘两个单位向量
float DotResult = Vector3.Dot(RoleForwardV, RoleToMonsterV.normalized);
float Jiaodu = Mathf.Acos(DotResult ) / Mathf.Deg2Rad;//这是两个向量夹角角度
Mathf.Acos(DotResult); //--它计算余弦值对应的弧度
Mathf.Acos(DotResult)/Mathf.Rad2Deg; //--它计算余弦值对应的角度
赠送一个完整的点乘、叉乘代码示例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class vEC : MonoBehaviour
{
public GameObject ONECUBE;
public GameObject onesphere;
// Dot 需要一个物体前方向量 连线向量
void Update()
{
Vector3 oneFront = ONECUBE.transform.forward;//拿到物体前方向量
Vector3 cubeTosphere =(ONECUBE.transform.position - onesphere.transform.position).normalized;
Debug.Log(cubeTosphere.magnitude);//(2,1,2)
float dotresult= Vector3.Dot(oneFront, cubeTosphere);
//cos(a)=dotresult
if (dotresult>0)
{
Debug.Log("0-90 前方");
//onesphere.transform.Translate(cubeTosphere*10f*Time.deltaTime);
}
float Jiaodu = Mathf.Acos(dotresult) / Mathf.Deg2Rad;//这是两个向量夹角角度
Debug.Log("两个向量的夹角是"+Mathf.Acos(dotresult)/Mathf.Deg2Rad+"度");
Debug.DrawRay(ONECUBE.transform.position,ONECUBE.transform.forward*100f);
Debug.DrawRay(ONECUBE.transform.position, cubeTosphere * 100f);
Vector3 oneCross = Vector3.Cross(oneFront, cubeTosphere);//向量叉乘X
Debug.DrawRay(oneFront, oneCross*100,Color.red);
}
}