Game Development Reference
In-Depth Information
Direction vectors usually don't have any units associated with them. We can give them a unit by
multiplying them with a scalar—for example, we can multiply a direction vector d = (0,1) with a
speed constant s = 100 m/s to get a velocity vector v = (0 × 100,1 × 100) = (0,100). It's always
a good idea to let your direction vectors have a length of 1. Vectors with a length of 1 are called
unit vectors . We can make any vector a unit vector by dividing each of its components by
its length:
(
)
d
'
=
d.x / d , d.y /
| d |
Remember that |d| just means the length of the vector d . Try it out. Say you want a direction
vector that points exactly northeast: d = (1,1). It might seem that this vector is already a unit
length, as both components are 1, right? Wrong:
(
)
*
*
d
=
sqrt 1 1
+
1 1
=
sqrt(2) ~ 1.44
=
You can easily fix that by making the vector a unit vector:
) (
) (
(
) (
)
d
'
=
d.x / d , d.y /
| d |
=
1 / d , 1/
| d | ~
=
1 / 1.44, 1 / 1.44
=
0.69, 0.69
This is also called normalizing a vector, which just means that we ensure it has a length of 1.
With this little trick, we can, for example, create a unit-length direction vector out of a distance
vector. Of course, we have to watch out for zero-length vectors, as we'd have to divide by zero
in that case!
A Little Trigonometry
It's time to turn to trigonometry for a minute. There are two essential functions in trigonometry:
cosine and sine . Each takes a single argument: an angle . You are probably used to specifying
angles in degrees (for example, 45° or 360°). In most math libraries, however, trigonometry
functions expect the angle in radians. We can easily do conversions between degrees and
radians using the following equations:
degreesToRadians(angleInDegrees) = angleInDegrees / 180 * pi
radiansToDegrees(angle) = angleInRadians / pi * 180
Here, pi is the beloved superconstant, with an approximate value of 3.14159265. pi radians
equal 180°, so that's how the preceding functions came to be.
So what do cosine and sine actually calculate, given an angle? They calculate the x and y
components of a unit-length vector relative to the origin. Figure 8-3 illustrates this.
 
Search WWH ::




Custom Search