獲取角度 ,官方提供了 Vector2.Angle 來得值,他的值是在 0 ,180之間
原始代碼是
public static float Angle(Vector3 from, Vector3 to)
{
return Mathf.Acos(Mathf.Clamp(Vector3.Dot(from.normalized, to.normalized), -1f, 1f)) * 57.29578f;
}
注意最后一個是 180/ 3.1415926... = 57.29578f;正常角度是 360,所以我們可以先 做出 -180,180之間
你可以
float angle_180(Vector2 from, Vector2 to)
{
Vector3 v3;
Vector3 v3_from = new Vector3(from.x, from.y, 1);
Vector3 v3_to = new Vector3(to.x , to.y , 1);
v3 = Vector3.Cross(v3_from, v3_to);
if (v3.z > 0)
{
return Vector2.Angle(from, to);
}
else
{
return -Vector2.Angle(from, to);
}
}
也可以這樣寫
float VectorAngle(Vector2 from, Vector2 to)
{
float angle;
Vector3 cross = Vector3.Cross(from, to);
angle = Vector2.Angle(from, to);
return cross.z > 0 ? -angle : angle;
}
0,360之間可以這樣寫
if (angle < 0)
{
angle = 360 + angle;
}
但是,我今天要說的不是這些,這些百度都可以知道。
我說的是 Vector2.Angle 的 bug以上的操作,僅僅對於 起始點0,0 有效,如果起始點 其他坐標,那么 他將會有誤差
那么我們改怎么做呢?
這樣寫,可以沒有誤差,注意 initPosition是目標坐標
Vector2 v2 = (mousePosition - initPosition).normalized;
float angle = Mathf.Atan2(v2.y, v2.x)*Mathf.Rad2Deg;
if(angle < 0)
angle = 360 + angle;
參考老外聊天,這個問題也是我 發現后 google 找的。
http://answers.unity3d.com/questions/444414/get-angle-between-2-vector2s.html
