Game Development Reference
In-Depth Information
to rotating, body-fixed coordinates so that you can apply the forces to the body; or you
might have to convert a body's velocity defined in global coordinates to body coordinates
so that you can use the velocity in force calculations.
Quaternion Operations
As with vectors and matrices, quaternions have their own rules for the various opera‐
tions that you'll need, such as multiplication, addition, subtraction, and so on. To make
it easy on you, we've included sample code in Appendix C that implements all of the
quaternion operations you'll need; however, we want to highlight a few of the more
important ones here.
The Quaternion class is defined with a scalar component, n , and vector component, v ,
where v is the vector, x i + y j + z k . The class has two constructors, one of which initializes
the quaternion to 0, and the other of which initializes the elements to those passed to
the constructor:
class Quaternion {
public:
float n; // number (scalar) part
Vector v; // vector part: v.x, v.y, v.z
Quaternion(void);
Quaternion(float e0, float e1, float e2, float e3);
.
.
.
};
Magnitude
The Magnitude method returns the magnitude of the quaternion according to the fol‐
lowing formula:
| q | = n 2 + x 2 + y 2 + z 2
This is similar to calculating the magnitude of a vector, except that for quaternions you
have to take the fourth term, the scalar n , into account.
Here's the code that calculates the magnitude for our Quaternion class:
inline float Quaternion::Magnitude(void)
{
return (float) sqrt(n*n + v.x*v.x + v.y*v.y + v.z*v.z);
}