UNITY3D兩個物體相(xiàng)對位置、角度、相對(duì)速度方向
2019/4/9 點擊:
using UnityEngine;
using System.Collections;// 兩物體相對位置判斷、追蹤相對速度方向、朝向等計算方向以及(jí)角(jiǎo)度
public class Direction : MonoBehaviour {
public Vector3 V1;
public Vector3 V2;
void Start()
{
// 為了方便理解便於(yú)計算,將向量在 Y 軸上的偏移量設置為 0
V1 = new Vector3( 3, 0, 4);
V2 = new Vector3( -4, 0, 3); // 分別(bié)取 V1,V2 方向上的 單位向量(隻是為了方便下麵計算)
V1 = V1.normalized;
V2 = V2.normalized; // 計算向量 V1,V2 點乘結果
// 即獲取 V1,V2夾角餘弦 cos(夾角)
float direction = Vector3.Dot(V1, V2);
Debug.LogError("direction : " + direction); // 夾角方向(xiàng)一般取(qǔ)(0 - 180 度)
// 如果取(0 - 360 度)
// direction >= 0 則夾角在 (0 - 90] 和 [270 - 360] 度之間
// direction < 0 則夾(jiá)角在(zài) (90 - 270) 度之間
// direction 無法確定具(jù)體角度 // 反餘弦求V1,V2 夾(jiá)角的弧度
float rad = Mathf.Acos(direction);
// 再將弧度轉換(huàn)為角度
float deg = rad * Mathf.Rad2Deg;
// 得到的 deg 為 V1,V2 在(0 - 180 度的夾角)還無法確定V1,V2 的相對夾角
// deg 還是無法確定具體角度 // 計算向量 V1, V2 的叉乘結果
// 得到垂直於 V1, V2 的向量, Vector3(0, sin(V1,V2夾角), 0)
// 即 u.y = sin(V1,V2夾角)
Vector3 u = Vector3.Cross(V1, V2);
Debug.LogError("u.y : " + u.y); // u.y >= 0 則夾角在 ( 0 - 180] 度之(zhī)間
// u.y < 0 則夾角在 (180 - 360) 度之間
// u.y 依然無法確定具體角度 // 結合 direction >0 、 u.y > 0 和 deg 的值
// 即可確定 V2 相對於 V1 的夾角
if (u.y >= 0) // (0 - 180]
{
if (direction >= 0)
{
// (0 - 90] 度
}
else
{
// (90 - 180] 度
}
}
else // (180 - 360]
{
if (direction >= 0)
{
// [270 - 360]
// 360 + (-1)deg
}
else
{
// (180 - 270)
}
} Debug.LogError(deg);
}
}
- 上一篇:unity3d角度偏移計算方法(fǎ) 2019/4/9
- 下一篇:UNITY3D 腳本實現(xiàn)鼠標控製物體旋轉 2019/4/9
