Appendix C. Quaternion Operations

This appendix implements a class called Quaternion that encapsulates all of the operations you need to handle quaternions when writing 3D rigid-body simulations.

Quaternion Class

The Quaternion class is defined with a scalar component, n, and vector component, v, where v is the vector, × 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);

     float      Magnitude(void);
     Vector     GetVector(void);
     float      GetScalar(void);
     Quaternion operator+=(Quaternion q);
     Quaternion operator-=(Quaternion q);
     Quaternion operator*=(float s);
     Quaternion operator/=(float s);
     Quaternion operator~(void) const { return Quaternion( n,
                                                           -v.x,
                                                           -v.y,
                                                           -v.z);}
};

// Constructor
inline     Quaternion::Quaternion(void)
{
     n   = 0;
     v.x = 0;
     v.y = 0;
     v.z = 0;
}

// Constructor
inline     Quaternion::Quaternion(float e0, float e1, float e2, float e3)
{
     n   = e0;
     v.x = e1;
     v.y = e2;
     v.z = e3;
}

Magnitude

The method Magnitude returns the magnitude of the quaternion according to the following formula:

|q| =

This is similar to calculating the magnitude of a vector except that for quaternions you have to take the fourth term, the ...

Get Physics for Game Developers, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.