• 您的位置:首頁 > 新聞動態(tài) > Unity3D

    UNITY3D兩個物體相對位置、角度、相對速度方向

    2019/4/9??????點(diǎn)擊:
    using UnityEngine;
    using System.Collections;
    
    // 兩物體相對位置判斷、追蹤相對速度方向、朝向等計算方向以及角度
    public class Direction : MonoBehaviour {
        public Vector3 V1;
        public Vector3 V2;
        void Start()
        {
            // 為了方便理解便于計算,將向量在 Y 軸上的偏移量設(shè)置為 0
            V1 = new Vector3( 3, 0, 4);
            V2 = new Vector3( -4, 0, 3);
    
            // 分別取 V1,V2 方向上的 單位向量(只是為了方便下面計算)
            V1 = V1.normalized;
            V2 = V2.normalized;
    
            // 計算向量 V1,V2 點(diǎn)乘結(jié)果
            // 即獲取 V1,V2夾角余弦    cos(夾角)
            float direction = Vector3.Dot(V1, V2);
            Debug.LogError("direction : " + direction);
    
            // 夾角方向一般?。? - 180 度)
            // 如果取(0 - 360 度)
            // direction >= 0 則夾角在 (0 - 90] 和 [270 - 360] 度之間
            // direction < 0 則夾角在 (90 - 270) 度之間
            // direction 無法確定具體角度
    
            // 反余弦求V1,V2 夾角的弧度
            float rad = Mathf.Acos(direction);
            // 再將弧度轉(zhuǎn)換為角度
            float deg = rad * Mathf.Rad2Deg;
            // 得到的 deg 為 V1,V2 在(0 - 180 度的夾角)還無法確定V1,V2 的相對夾角
            // deg 還是無法確定具體角度
    
            // 計算向量 V1, V2 的叉乘結(jié)果
            // 得到垂直于 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] 度之間
            // u.y < 0 則夾角在 (180 - 360) 度之間
            // u.y 依然無法確定具體角度
    
            // 結(jié)合 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);
        }
    }