Game Development Reference
In-Depth Information
r = r ;
t h e t a
+=
P I ;
}
/ /
T h e t a
o u t
o f
r a n g e ?
Note
t h a t
t h i s
i f ( )
check
i s
n o t
/ /
s t r i c t l y
n e c e s s a r y ,
b u t
we
t r y
t o
a v o i d
d o i n g
f l o a t i n g
/ /
p o i n t
o p e r a t i o n s
i f
t h e y
a r e n ' t
n e c e s s a r y .
Why
/ /
i n c u r
f l o a t i n g
p o i n t
p r e c i s i o n
l o s s
i f
we don ' t
/ /
need
t o ?
i f
( f a b s ( t h e t a ) > P I )
{
/ /
O f f s e t
by
P I
t h e t a
+=
P I ;
/ /
Wrap
i n
r a n g e
0 . . . TWOPI
=
t h e t a
f l o o r ( t h e t a
/
TWOPI )
TWOPI ;
/ /
Undo
o f f s e t ,
s h i f t i n g
a n g l e
back
i n
r a n g e
P I . . . P I
t h e t a
=
P I ;
}
}
Listing 7.1
Converting polar coordinates to canonical form
Picky readers may notice that while this code ensures that θ is in the
closed interval [−π,+π], it does not explicitly avoid the case where θ = −π.
The value of π is not exactly representable in floating point. In fact, because
π is an irrational number, it can never be represented exactly in floating
point, or with any finite number of digits in any base, for that matter!
The value of the constant PI in our code is not exactly equal to π, it's
the closest number to π that is representable by a float . Using double-
precision arithmetic can get us closer to the exact value, but it is still not
exact. So you can think of this function as returning a value from the open
interval (−π,+π).
7.1.3
Converting between Cartesian and
Polar Coordinates in 2D
This section describes how to convert between the Cartesian and polar
coordinate systems in 2D. By the way, if you were wondering when we were
going to make use of the trigonometry that we reviewed in Section 1.4.5,
this is it.
Figure 7.4 shows the geometry involved in converting between polar and
Cartesian coordinates in 2D.
Converting polar coordinates (r,θ) to the corresponding Cartesian coor-
dinates follows almost immediately from the definitions of sine and cosine:
Converting 2D polar
coordinates to Cartesian
x = r cosθ;
y = r sinθ.
(7.1)
 
Search WWH ::




Custom Search