WTF XNA, Quaternion to Euler conversion
March 11th, 2008
Okay, so, XNA has quaterions, so you have {x,y,z,w}
Lets say you want to turn that back into {yaw,pitch,roll}
So you hit up Wikipedia and find some equations:
{x,y,z,w} = {q0,q1,q2,q3} right?
Well…NOOO, freaking XNA, that’s not right, hmm, perhaps its alphabetical?
{w,x,y,z} = {q0,q1,q2,q3}???
Once again, XNA slaps you around for nooo reason, here’s the right match-up:
{x,y,z,w} = {q2,q1,q3,q0}
{w,y,x,z} = {q0,q1,q2,q3}
Also, here’s some code to turn a quaterion into a vector of pitch,yaw,roll
public Vector3 QuaternionToEuler(Quaternion rotation)
{
float q0 = rotation.W;
float q1 = rotation.Y;
float q2 = rotation.X;
float q3 = rotation.Z;
Vector3 radAngles = new Vector3();
radAngles.X = (float)Math.Atan2(2 * (q0 * q1 + q2 * q3), 1 – 2 * (Math.Pow(q1, 2) + Math.Pow(q2, 2)));
radAngles.Y = (float)Math.Asin(2 * (q0 * q2 – q3 * q1));
radAngles.Z = (float)Math.Atan2(2 * (q0 * q3 + q1 * q2), 1 – 2 * (Math.Pow(q2, 2) + Math.Pow(q3, 2)));
Vector3 angles = new Vector3();
angles.X = MathHelper.ToDegrees(radAngles.X);
angles.Y = MathHelper.ToDegrees(radAngles.Y);
angles.Z = MathHelper.ToDegrees(radAngles.Z);
return angles;
}
3 Comments Add your own
1. Scott Peal | April 6th, 2009 at 2:36 pm
I put in the following and expected to get back something different:
Quaternion quat1 = Quaternion.CreateFromAxisAngle(Vector3.UnitY, (float)Math.PI); //180 degres
Quaternion quat2 = Quaternion.CreateFromAxisAngle(Vector3.UnitX, (float)Math.PI); //180 degres
Quaternion quat = quat1 * quat2;
?v
{X:5.008956E-06 Y:-5.008956E-06 Z:180}
X: 0.00000500895567
Y: -0.00000500895567
Z: 180.0
I would have expected to get:
X: 180
Y: 180
Z: 0
2. Scott Peal | April 6th, 2009 at 2:37 pm
Thread I am also trying to sind a solution and mentioned your post: http://forums.xna.com/forums/p/28687/159870.aspx#159870
3. RohoMech | April 7th, 2009 at 8:57 am
Hi Scott,
Yea, it looks like what I’ve posted isn’t working for your case.
Though, this code didn’t make its way into production, sorry you’re that found the issue.
The approach we ended up taking was to store both the Euler angles along with the quaternion.
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed