Game Development Reference

In-Depth Information

In other words, the length of the normalized vector is 1 unit. If
v
is a non-unit vector

with components
x
,
y
, and
z
, then we can calculate the unit vector
u
from
v
as follows:

u
=
v
/ |
v
| = (x / |
v
|)
I
+ (y / |
v
|)
j
+ (z / |
v
|)
k

Here |
v
| is simply the magnitude, or length, of vector
v
as described earlier.

Here's the code that converts our
Vector
class vector to a unit vector:

inline void Vector::Normalize(void)

{

float m = (float) sqrt(x*x + y*y + z*z);

if(m <= tol) m = 1;

x /= m;

y /= m;

z /= m;

if (fabs(x) < tol) x = 0.0f;

if (fabs(y) < tol) y = 0.0f;

if (fabs(z) < tol) z = 0.0f;

}

In this function,
tol
is a float type tolerance; for example:

float const tol = 0.0001f;

Reverse

The
Reverse
method reverses the direction of the vector, which is accomplished by

simply taking the negative of each component. After calling
Reverse
, the vector will

point in a direction opposite to the direction it was pointing before
Reverse
was called:

inline void Vector::Reverse(void)

{

x = -x;

y = -y;

z = -z;

}

This operation is illustrated in
Figure A-3
.