2012-02-06 122 views
1

我在我的遊戲中使用四元數來計算一些基本角度。如何從四元數軸上得到投影角度?

現在我正在試圖得到一個四元數的角度,給定一個軸。所以,給定一個四元數和一個新的軸。我可以得到投影角度嗎?

對我來說,這似乎是一個可靠的方法來計算兩個向量之間的符號角度。代碼是用Unity3D C#編寫的,但這不一定是這種情況。這更多的是一種通用的方法。

public static float DirectionalAngle(Vector3 from, Vector3 to, Vector3 up) 
{ 
    // project the vectors on the plane with up as a normal 
    Vector3 f = Vector3.Exclude(up, from); 
    Vector3 t = Vector3.Exclude(up, to); 

    // creates an angle-axis rotation 
    Quaternion q = Quaternion.FromToRotation(f, t); 

    // do something to get the angle out of the quaternion, 
    // given the new axis. 
    // TODO: Make this method. Doesn't exist. 
    Quaternion q2 = Quaternion.GetAngleFromAxis(q, Vector3.right); 

    return q2.Angle(q2); 
} 

我總是可以從四元數,以及x,y,z,w和歐拉角度獲得角度和軸。但我沒有看到從軸上的四元數獲得投影角度的方法。

回答

1

我發現它!我必須做的唯一事情就是旋轉四元數,使其在本地空間中定向。對於我測試過的所有飛機,該方法似乎都很合理。

public static float DirectionalAngle(Vector3 from, Vector3 to, Vector3 up) 
{ 
    // project the vectors on the plane with up as a normal 
    Vector3 f = Vector3.Exclude(up, from); 
    Vector3 t = Vector3.Exclude(up, to); 

    // rotate the vectors into y-up coordinates 
    Quaternion toZ = Quaternion.FromToRotation(up, Vector3.up); 
    f = toZ * f; 
    t = toZ * t; 

    // calculate the quaternion in between f and t. 
    Quaternion fromTo = Quaternion.FromToRotation(f,t); 

    // return the eulers. 
    return fromTo.eulerAngles.y; 
} 
+0

如果我理解正確,你不是在尋找投影向量'f'和't'之間的角度嗎?在這種情況下,這應該足夠了:'Vector3.Angle(f,t)' – 2012-02-06 21:31:25

+0

沒有,這會給我無符號的角度。我需要兩者的簽名(方向)角度。所以真的,*從*到*到*。但我不喜歡常用的'atan2'方法。 – Marnix 2012-02-06 22:20:02

+1

'atan2'方法真的是要走的路。這是非常低效的(而且仍然包括一個atan2)。 – JCooper 2012-02-07 19:36:01