Game Development Reference
In-Depth Information
we move to a different quadrant in the plane, but the ratio y/x doesn't
change.
Because of these problems, the complete equation for conversion from
Cartesian to polar coordinates requires some “if statements” to handle each
quadrant, and is a bit of a mess for “math people.” Luckily, “computer
people” have the atan2 function, which properly computes the angle θ for
all x and y, except for the pesky case at the origin. Borrowing this notation,
let's define an atan2 function we can use in this topic in our math notation:
8
<
0, x = 0,y = 0,
+90 o , x = 0,y > 0,
−90 o , x = 0,y < 0,
arctan(y/x), x > 0,
arctan(y/x) + 180 o , x < 0,y ≥ 0,
arctan(y/x) − 180 o , x < 0,y < 0.
The atan2 function used
in this topic
atan2(y,x) =
(7.2)
:
Let's make two key observations about Equation (7.2). First, following the
convention of the atan2 function found in the standard libraries of most
computer languages, the arguments are in the “reverse” order: y,x. You
can either just remember that it's reversed, or you might find it handy to
remember the lexical similarity between atan2(y,x) and arctan(y/x). Or
remember that tanθ = sinθ/cosθ, and θ = atan2(sinθ,cosθ).
Second, in many software libraries, the atan2 function is undefined at
the origin, when x = y = 0. The atan2 function we are defining for use in
our equations in the text of this topic is defined such that atan2(0,0) = 0.
In our code snippets, we use the library function atan2 and explicitly han-
dle the origin as a special case, but in our equations, we use the abstract
function atan2, which is defined at the origin. (Note the difference in type-
face.)
Back to the task at hand: computing the polar angle θ from a set of
2D Cartesian coordinates. Armed with the atan2 function, we can easily
convert 2D Cartesian coordinates to polar form:
r =
x 2 + y 2 ;
θ = atan2(y,x).
2D Cartesian to polar
coordinate conversion
The C code in Listing 7.2 shows how to convert a Cartesian (x,y) co-
ordinate pair to the corresponding canonical polar (r,θ) coordinates.
/ /
I n p u t :
C a r t e s i a n
c o o r d i n a t e s
f l o a t
x , y ;
/ /
Output :
p o l a r
r a d i a l
d i s t a n c e ,
and
a n g l e
i n
RADIANS
f l o a t
r ,
t h e t a ;
/ /
Check
i f
we
a r e
a t
t h e
o r i g i n
Search WWH ::




Custom Search