Game Development Reference
In-Depth Information
A change in position, given as a vector, can be split into two elements:
a
=
d n
[2.1]
where d is the straight-line distance of the change (called the “magnitude” of the
vector) and n is the direction of the change. The vector n represents a change, whose
straight-line distance is always 1, in the same direction as the vector a .
We c a n fi n d d using the three-dimensional version of Pythagoras's theorem,
which has the formula
x 2
d
=|
a
|=
+
y 2
+
z 2
where x , y ,and z are the three components of the vector and
|
a
|
is the magnitude of
avector.
We c a n u s e e q u a t i o n 2 . 1 t o fi n d n :
1
d a
a
=
n
=
[2.2]
where
a is a common (but not universal) notation for the unit-length direction of a .
The equation is sometimes written as
a
a
=
|
a
|
The process of finding just the direction n from a vector is called “normalizing”;
the result is sometimes called the “normal” form of the vector (i.e., n is the normal
form of a in the preceding equations). It is a common requirement in several algo-
rithms.
We can add functions to find the magnitude of the vector and its direction and
perform a normalization:
Excerpt from include/cyclone/precision.h
/** Defines the precision of the square root operator. */
#define real_sqrt sqrtf
Excerpt from include/cyclone/core.h
class Vector3
{
// ... Other Vector3 code as before ...
/** Gets the magnitude of this vector. */
real magnitude() const
{
return real_sqrt(x*x+y*y+z*z);
}