Home Articles Tutorials Resources About
Quaternions for rotation   Last update: 2008-07-09 19: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)

    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);

        return Quaternion.CreateFromAxisAngle(axis, MathHelper.Pi);
        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);

        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
XNA info is sponsored by vector4. All content is copyright © 2005-2017 by its respective authors | About XNA info | Terms of Use | RSS feed