rotating a quaternion on 1 axis?

William picture William · Dec 14, 2010 · Viewed 23.7k times · Source

I have a model rotated by a quaternion. I can only set the rotation, I can't add or subtract from anything. I need to get the value of an axis, and than add an angle to it (maybe a degree or radian?) and than re-add the modified quaternion.

How can I do this? (answer on each axis).

Answer

sje397 picture sje397 · Dec 14, 2010

You can multiply two quaternions together to produce a third quaternion that is the result of the two rotations. Note that quaternion multiplication is not commutative, meaning order matters (if you do this in your head a few times, you can see why).

You can produce a quaternion that represents a rotation by a given angle around a particular axis with something like this (excuse the fact that it is c++, not java):

Quaternion Quaternion::create_from_axis_angle(const double &xx, const double &yy, const double &zz, const double &a)
{
    // Here we calculate the sin( theta / 2) once for optimization
    double factor = sin( a / 2.0 );

    // Calculate the x, y and z of the quaternion
    double x = xx * factor;
    double y = yy * factor;
    double z = zz * factor;

    // Calcualte the w value by cos( theta / 2 )
    double w = cos( a / 2.0 );

    return Quaternion(x, y, z, w).normalize();
}

So to rotate around the x axis for example, you could create a quaternion with createFromAxisAngle(1, 0, 0, M_PI/2) and multiply it by the current rotation quaternion of your model.