Showing posts with label forward. Show all posts
Showing posts with label forward. Show all posts

Friday, November 11, 2011

Quaternion Math: Getting local axis vectors from a quaternion

If your game uses the standard coordinate system of X representing left/right vector, Y representing up/down vector, and Z representing forward/backward vector, then this following method should allow you to convert a quaternion into a vector that represents 'forward', 'up', and 'right'.

I've found these extremely useful, as this is much more efficient than converting the quaternion into a matrix just so you can extract the column/row you need from the matrix for the vector you want.

Vector3 Quaternion::GetForwardVector() const
{
    return Vector3( 2 * (x * z + w * y), 
                    2 * (y * x - w * x),
                    1 - 2 * (x * x + y * y));
}

Vector3 Quaternion::GetUpVector() const
{
    return Vector3( 2 * (x * y - w * z), 
                    1 - 2 * (x * x + z * z),
                    2 * (y * z + w * x));
}

Vector3 Quaternion::GetRightVector() const
{
    return Vector3( 1 - 2 * (y * y + z * z),
                    2 * (x * y + w * z),
                    2 * (x * z - w * y));
}