Quaternions in XNA

advertisement
Quaternions in XNA:
XNA comes equipped with a Quaternion data structure (struct) that can be used for the rotation
of points/vectors in a simple manner. The structure contains 4 data members:
X:
Y:
Z:
W:
x-component of the imaginary vector
y-component of the imaginary vector
z-component of the imaginary vector
real-valued scalar of the quaternion
The common quaternion operations are all included within the Quaternion data structure. For a
complete list of the members of a Quaternion instance, visit http://msdn.microsoft.com/enus/library/microsoft.xna.framework.quaternion_members.aspx . Some example uses of these
member functions follow:
Quaternion[] quaternions
= new Quaternion[6];
// Addition
quaternions[0]
= q1 + q2;
// Multiplication (not commutative)
quaternions[1]
= q2 * q1;
// Identity quaternion
quaternions[2]
= Quaternion.Identity;
// Magnitude/Length
float Magnitude
= quaternions[1].Length();
// Inverse quaternion
quaternions[3]
= Quaternion.Inverse(quaternions[0]);
// Normalization (force length == 1)
quaternions[4]
= Quaternion.Normalize(quaternions[3]);
// Conjugate (negate the imaginary vector)
quaternions[5]
= Quaternion.Conjugate(q2);
// Linear interpolation
quaternions[6]
= Quaternion.Lerp(q1, q2, 0.75f);
How do we construct a quaternion that represents a particular rotation on an arbitrary axis?
Using the built-in approach:
// Create a quaternion from a rotation axis and angle (radians)
Quaternion rotation = Quaternion.CreateFromAxisAngle(RotationAxis, RotationAngle);
Manually:
// Creating a quaternion from a rotation axis and angle (radians) manually
Quaternion rotation = new Quaternion( RotationAxis * Math.Sin(RotationAngle/2.0f),
Math.Cos(RotationAngle/2.0f));
How do we rotate a point/vector using a quaternion?
Using the built-in approach:
// The “oldVector” is rotated by the quaternion and the result is stored in newVector
Vector3 newVector = Vector3.Transform(oldVector, rotationQuaternion);
Manually:
Another way to rotate a point/vector is to use the quaternion property:
v′ = Qrot * v * Qrot-1
// We create a quaternion that represents the untransformed vector
Quaternion oldVectorQ = new Quaternion(oldVector, 0.0f);
// Rotate that vector using quaternions
Quaternion newVectorQ = rotationQ * oldVectorQ * Quaternion.Inverse(rotationQ);
// The transformed vector is contained within newVectorQ.xyz
Vector3 newVector = new Vector3(newVectorQ.X, newVectorQ.Y, newVectorQ.Z);
Converting a quaternion to a rotation matrix:
// A quaternion can be converted into a rotation matrix
Matrix rotationMatrix = Matrix.CreateFromQuaternion(rotationQuaternion);
Download