Game Development Reference
In-Depth Information
Figure 8-3. Cosine and sine produce a unit vector, with its endpoint lying on the unit circle
Given an angle, we can therefore create a unit-length direction vector like this:
( ) ( )
(
)
v
=
cos angle , sin angle
We can go the other way around, as well, and calculate the angle of a vector with respect to the
x axis:
( )
angle
=
atan2 v.y, v.x
The atan2 function is actually an artificial construct. It uses the arcus tangent function (which is
the inverse of the tangent function, another fundamental function in trigonometry) to construct
an angle in the range of -180° to 180° (or -pi to pi , if the angle is returned in radians). The
internals are somewhat involved, and do not matter all that much in this discussion. The
arguments are the y and x components of a vector. Note that the vector does not have to be a
unit vector for the atan2 function to work. Also, note that the y component is usually given first,
and then the x component—but this depends on the selected math library. This is a common
source of errors.
Try a few examples. Given a vector v = (cos(97°), sin(97°)), the result of atan2(sin(97°),cos(97°))
is 97°. Great, that was easy. Using a vector v = (1,-1), you get atan2(-1,1) = -45°. So if your
vector's y component is negative, you'll get a negative angle in the range 0° to -180°. You can
fix this by adding 360° (or 2 pi ) if the output of atan2 is negative. In the preceding example, you
would then get 315°.
The final operation we want to be able to apply to our vectors is rotating them by some angle.
The derivations of the equations that follow are again rather involved. Luckily, we can just use
these equations as is, without knowing about orthogonal base vectors. (Hint: That's the key
phrase to search for on the Web if you want to know what's going on under the hood.) Here's the
magical pseudocode:
( )
( )
'
*
v.x
=
cos angle
v.x
sin angle
* v.y
( )
( )
'
*
* v.
v.y
=
sin angle
v.x
+
cos angle
y
 
Search WWH ::




Custom Search