**Quaternions for rotation**Last update: 2008-07-09 20:21:37 by Rim van Wersch

This sample demonstrates the very basics on how to use quaternions for rotations and how to interpolate between them. It comes with an XNA adaptation of some handy Ogre3D code to fetch the quaternion representing the rotation between two vectors, which you'll find below.

private Quaternion GetRotation(Vector3 src, Vector3 dest) { src.Normalize(); dest.Normalize(); float d = Vector3.Dot(src, dest); if (d >= 1f) { return Quaternion.Identity; } else if (d < (1e-6f - 1.0f)) { Vector3 axis = Vector3.Cross(Vector3.UnitX, src); if (axis.LengthSquared() == 0) { axis = Vector3.Cross(Vector3.UnitY, src); } axis.Normalize(); return Quaternion.CreateFromAxisAngle(axis, MathHelper.Pi); } else { float s = (float)Math.Sqrt((1 + d) * 2); float invS = 1 / s; Vector3 c = Vector3.Cross(src, dest); Quaternion q = new Quaternion(invS * c, 0.5f * s); q.Normalize(); return q; } }Below you'll find the sample which uses the code above to rotate an arrow model to the desired heading. Just click somewhere and the arrow will orient itself accordingly, smoothly slerping between the current and target rotation.

**Files for this resource**

Filename | Size |

QuaternionRotation.zip | 34.0 KB |