172 4. 3D Math for Games

`This is analogous to the reversal that occurs when transposing or inverting`

matrix products.

`4.4.3. Rotating Vectors with Quaternions`

How can we apply a quaternion rotation to a vector? The fi rst step is to rewrite

the vector in quaternion form. A vector is a sum involving the unit basis vectors

i, j, and k. A quaternion is a sum involving i, j, and k, but with a fourth scalar

term as well. So it makes sense that a vector can be writt en as a quaternion

with its scalar term qS equal to zero. Given the vector v, we can write a cor-

responding quaternion v = [ v 0 ] = [ vx vy vz 0 ].

In order to rotate a vector v by a quaternion q, we pre-multiply the vec-

tor (writt en in its quaternion form v) by q and then post-multiply it by the

inverse quaternion, q–1. Therefore, the rotated vector v’ can be found as fol-

lows:

`This is equivalent to using the quaternion conjugate, because our quaternions`

are always unit length:

(4.4)

The rotated vector v’ is obtained by simply extracting it from its quaternion

form v’.

Quaternion multiplication can be useful in all sorts of situations in real

games. For example, let’s say that we want to fi nd a unit vector describing the

direction in which an aircraft is fl ying. We’ll further assume that in our game,

the positive z-axis always points toward the front of an object by convention.

So the forward unit vector of any object in model space is always FM ≡ [ 0 0 1 ]

by defi nition. To transform this vector into world space, we can simply take

our aircraft ’s orientation quaternion q and use it with Equation (4.4) to rotate

our model-space vector FM into its world space equivalent FW (aft er converting

these vectors into quaternion form, of course):

`4.4.3.1. Quaternion Concatenation`

Rotations can be concatenated in exactly the same way that matrix-based trans-

formations can, by multiplying the quaternions together. For example, consid-

er three distinct rotations, represented by the quaternions q1 , q 2 , and q3 , with

matrix equivalents R1 , R 2 , and R 3. We want to apply rotation 1 fi rst, followed

by rotation 2 and fi nally rotation 3. The composite rotation matrix Rnet can be

found and applied to a vector v as follows:

`v′==rotate(q, )v qvq*.`

`F WM==qF q−−^11 q [0 0 1 0] q.`

`v′==rotate(q, )v qvq .−^1`