赞
踩
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DotAndCross : MonoBehaviour {
public Transform a;
public Transform b;
// Update is called once per frame
void Update () {
GetAngle( a.position, b.position);
}
//点积,点乘
public void TestDot(Vector3 a, Vector3 b)
{
//a·b=|a|·|b|cos<a,b> 点乘求角度 ,叉乘求方向
//<a,b>= arccos(a·b / (|a|·|b|)) arccos 反余弦 (点向乘/1)
//根据点乘的正负值,得到夹角大小范围,>0,则夹角(0,90)<0,则夹角(90,180),可以利用这点判断一个多边形是面向摄像机还是背向摄像机。
float result = Vector3.Dot(a.normalized, b.normalized);
float radius = Mathf.Acos(result) * Mathf.Rad2Deg;
print("result :" + result);
print("radius :" + radius);
}
//叉乘
public void TestCross(Vector3 a, Vector3 b)
{
//计算向量 a、b 的叉积,结果为 向量
//模长|c| = |a||b| sin<a,b> <a,b> 角度 = Asin( |c| /|a||b|)
Vector3 c = Vector3.Cross(a.normalized ,b.normalized);
float d = Vector3.Distance(Vector3.zero,c);
float radius = Mathf.Asin(d)*Mathf.Rad2Deg;
print("radius :" + radius);
print(c.y);
if (c.y >0)
{
print("b在a的左边");
}
if (c.y < 0)
{
print("b在a的右边");
}
if (c.y == 0)
{
print("a和b平行");
}
}
// 获取两个向量的夹角 Vector3.Angle 只能返回 [0, 180] 的值
// 如真实情况下向量 a 到 b 的夹角(80 度)则 b 到 a 的夹角是(-80)
// 通过 Dot、Cross 结合获取到 a 到 b, b 到 a 的不同夹角
public void GetAngle(Vector3 a, Vector3 b)
{
Vector3 c = Vector3.Cross(a, b);
float angle = Vector3.Angle(a, b);
print(c.normalized);
print(Vector3.Cross(a.normalized, b.normalized));
print(Vector3.Dot(c.normalized, Vector3.Cross(a.normalized, b.normalized)));
// b 到 a 的夹角 Mathf.Sign (f) 当 f 为正或为0 返回1,为负返回-1。
float sign = Mathf.Sign(Vector3.Dot(c.normalized, Vector3.Cross(a.normalized, b.normalized)));
float signed_angle = angle * sign;
Debug.Log("b -> a :" + signed_angle);
// a 到 b 的夹角
sign = Mathf.Sign(Vector3.Dot(c.normalized, Vector3.Cross(b.normalized, a.normalized)));
signed_angle = angle * sign;
Debug.Log("a -> b :" + signed_angle);
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。