Transform
屬性 | 說明 |
---|---|
Matrix4x4 localToWorldMatrix: | 本地坐標->世界坐標的矩陣信息。 |
Matrix4x4 worldToLocalMatrix: | 世界坐標->本地坐標的矩陣信息。 |
方法 | 說明 |
---|---|
Vector3 TransformDirection(Vector3 direction): | 本地坐標->世界坐標,不受位置和縮放影響(只旋轉坐標方向)。 |
Vector3 TransformPoint(Vector3 position): | 本地坐標->世界坐標,受位置和縮放影響。 |
Vector3 TransformVector(Vector3 vector): | 本地坐標->世界坐標,不受位置影響,受縮放影響。 |
方法 | 說明 |
---|---|
Vector3 InverseTransformDirection(Vector3 direction): | 世界坐標->本地坐標,不受位置和縮放影響(只旋轉坐標方向)。 |
Vector3 InverseTransformPoint(Vector3 position): | 世界坐標->本地坐標,受位置和縮放影響。 |
Vector3 InverseTransformVector(Vector3 vector): | 世界坐標->本地坐標,不受位置影響,受縮放影響。 |
transform.position=new Vector3(10,0,0);
transform.eulerAngles=new Vector3(0,90,0);
transform.localScale=new Vector3(0.5f,0,0.5f);
Vector3 relative=transform.InverseTransformDirection(new Vector3(5,0,5));//轉換結果見下圖A
Debug.Log(relative);//output: (-5, 0, 5)
relative=transform.InverseTransformPoint(new Vector3(5,0,5));//轉換結果見下圖B
Debug.Log(relative);//output:(-10, 0, -10)
relative=transform.InverseTransformVector(new Vector3(5,0,5));//轉換結果見下圖C
Debug.Log(relative);//output:(-10, 0, 10)
圖A:
圖B:
圖C:
旋轉向量
//將向量的方向轉換為四元數
//x、y、z旋轉角度都為0,就是Vector3.forward的方向
Quaternion qua0=new Quaternion();
Debug.Log(qua0.eulerAngles);//輸出:(0.0, 0.0, 0.0)
//同上
Quaternion qua1=Quaternion.LookRotation(Vector3.forward);
Debug.Log(qua1.eulerAngles);//輸出:(0.0, 0.0, 0.0)
//將向量Vector3.right的方向轉換為四元數
Quaternion qua2=Quaternion.LookRotation(Vector3.right);
Debug.Log(qua2.eulerAngles);//輸出: (0.0, 90.0, 0.0)
//向量(1,0,0)繞Y軸旋轉90度。
Vector3 a=new Vector3(1,0,0);
Vector3 b=Quaternion.AngleAxis(90, Vector3.up)*a;
Debug.Log(b);//輸出:(0.0, 0.0, -1.0)
//向量(1,1,0)旋轉到Vector3.right的方向(左視圖)
Vector3 e=new Vector3(1,1,0);
Vector3 f=Quaternion.LookRotation(Vector3.right)*e;
Debug.Log(f);//輸出: (0.0, 1.0, -1.0)
//將一個向量旋轉到Transform組件的旋轉角度
Vector3 f=new Vector3(0,0,1);
f=transform.rotation*f;
Quaternion.LookRotation (Vector3 forward, Vector3 upwards= Vector3.up);
現在有兩個對象,如下圖:
梯子:旋轉歐拉角度為x=0,y=90,z=22。
狗:旋轉歐拉角度為x=0,y=0,z=0。
求狗爬上梯子時的旋轉歐拉角?
var ladder=new GameObject();
ladder.transform.eulerAngles=new Vector3(0f,90f,22f);
Debug.Log(ladder.transform.up);//ouput:(0.0,0.9,0.4)
Debug.Log(ladder.transform.right);//ouput:(0.0,0.1,-0.9)
var rotation=Quaternion.LookRotation(ladder.transform.up,ladder.transform.right);
//dog.transform.rotation=rotation;
Debug.Log(rotation.eulerAngles);//output:(292,0.0,0.0)