2012-02-06 119 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