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