點、向量、方向在局部與世界坐標系轉換的對比


局部與世界坐標系除了在父子關系的物體中有重要的應用(父子物體中,局部坐標系與世界坐標系的區別

 

在多個同級物體間也有重要應用,(例如圍繞移動的物體旋轉,攝像機跟隨等)

1.某個點在局部坐標系與世界坐標系的轉換    
   worldPosition = target.transform.TransformPoint(localPosition );
   localPosition = target.transform.InverseTransformPoint(worldPosition );
2.某個向量在局部坐標系與世界坐標系的轉換
   worldVector = target.transform.TransformVector(localVector);
   localVector = target.transform.InverseTransfromVector(worldVector);
以上兩者區別:
   在轉換過程中,point以target的位置為起點做變換計算(適用於計算在物體運動中的固定偏移位置),vector以世界坐標系零點為起點做變換計算。
3.某個方向在局部坐標系與世界坐標系的轉換
   worldDirection = target.transform.TransformDirection(localDirection);
   localDirection = target.transform.TransformDirection(worldDirection);
以上三者區別:
   在轉換過程中,point和vector均受物體的縮放影響(等比例改變),direction以世界坐標系零點為起點,不受target位置、縮放的影響,適用於計算物體運過程中固定大小方向的受力或速度。
 

應用:

圍繞移動物體的y軸旋轉
源碼分享:
 1 public class FollowRotate : MonoBehaviour {
 2     public GameObject m_Target;                             // 目標物體
 3     public float m_RotateSpeed = 1F;                        // 旋轉速度
 4     private Vector3 m_RelativePosition;                     // 相對位置
 5     // Use this for initialization
 6     void Start () {
 7         // 獲取相對於目標物體的相對位置
 8         m_RelativePosition = m_Target.transform.InverseTransformPoint(transform.position);        
 9     }
10     
11     // Update is called once per frame
12     void Update () {
13         // 根據物體的相對位置計算物體的旋轉后的相對位置(始終圍繞目標的y軸旋轉)
14         m_RelativePosition = new Vector3
15         (
16             m_RelativePosition.x * Mathf.Cos(Time.deltaTime * m_RotateSpeed) - m_RelativePosition.z * Mathf.Sin(Time.deltaTime * m_RotateSpeed),
17             m_RelativePosition.y,
18             m_RelativePosition.z * Mathf.Cos(Time.deltaTime * m_RotateSpeed) + m_RelativePosition.x * Mathf.Sin(Time.deltaTime * m_RotateSpeed)
19         );
20         // 將旋轉后的相對位置轉化為世界位置,賦值
21         transform.position = m_Target.transform.TransformPoint(m_RelativePosition);
22     }
23 }
24  

 

攝像機跟隨

源碼分享:

 1 public class CameraFollowController : MonoBehaviour 
 2 {
 3     public GameObject m_Target;                             // 玩家
 4     public Vector3 m_Offset;                                // 相對玩家的偏移位置
 5     public float m_SmoothTime = 0.3F;                       // 平滑移動時間
 6 
 7     private Vector3 m_Velocity = Vector3.zero;              // 攝像機移動速度
 8     private Vector3 m_DestPosition;                         // 攝像機目的地位置
 9 
10     void Update ()
11     {
12         // 轉向 - 攝像機看向目標點位置
13         transform.LookAt(m_Target.transform.position);
14         // 獲取攝像機目的地位置 - 將相對於目標位置的偏移位置轉化為世界坐標
15         m_DestPosition = m_Target.transform.TransformPoint(m_Offset);
16         // 平滑阻尼移動攝像機
17         transform.position = Vector3.SmoothDamp(transform.position, m_DestPosition, ref m_Velocity, m_SmoothTime);
18     }
19 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM