unity中向量点乘

补充知识 调试画线

// 画线段
// 前两个参数 分别是 起点 终点
Debug.DrawLine(this.transform.position, this.transform.position + this.transform.forward, Color.red);
Debug.DrawRay(this.transform.position, this.transform.position + this.transform.forward, Color.white);

通过点乘判断对象方位

Debug.DrawRay(this.transform.position, this.transform.forward, Color.red);
Debug.DrawRay(this.transform.position, target.position - this.transform.position, Color.white);

Vector3 提供了计算点乘的方法----Dot

得到两个向量的点乘结果
向量a 点乘 向量b 的结果

float doResult = Vector3.Dot(this.transform.forward, target.position - this.transform.position);
if (doResult >= 0)
{
    print("他在我前方");
}
else
{
    print("他在我后方");
}

通过点乘推导公式算出夹角

// 步骤
// 1.用单位向量算出点乘结果
doResult = Vector3.Dot(this.transform.forward, (target.position - this.transform.position).normalized);
// 2.用反三角函数得出角度
print("角度" + Mathf.Acos(doResult) * Mathf.Rad2Deg);

Vector3中提供的计算夹角的方法 --- Angle

Vector3.Angle(this.transform.forward, target.position - this.transform.position);

猜你喜欢

转载自blog.csdn.net/m0_73113333/article/details/143022058