Game Development Reference
In-Depth Information
As with 2D polar coordinates, computing r is a straightforward appli-
cation of the distance formula:
x 2 + y 2 + z 2 .
r =
As before, the singularity at the origin, where r = 0, is handled as a special
case.
The heading angle is surprisingly simple to compute using our atan2
function:
h = atan2(x,z).
The trick works because atan2 uses only the ratio of its arguments and
their signs. By examining Equation (7.3), we notice that the scale factor
of r cosp is common to both x and z. Furthermore, by using canonical
coordinates, we are assuming r > 0 and −90 o ≤ p ≤ 90 o ; thus, cosp ≥ 0
and the common scale factor is always nonnegative. The Gimbal lock case
is dealt with by our definition of atan2.
Finally, once we know r, we can solve for p from y:
y = −r sinp,
−y/r = sinp,
p = arcsin(−y/r).
The arcsin function has a range of [−90 o ,90 o ], which fortunately coincides
with the range for p within the canonical set.
Listing 7.4 illustrates the entire procedure.
/ /
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 , z ;
/ /
Output
r a d i a l
d i s t a n c e
f l o a t
r ;
/ /
Output
a n g l e s
i n
r a d i a n s
f l o a t
h e a d i n g ,
p i t c h ;
/ /
D e c l a r e
a
few
c o n s t a n t s
c o n s t
f l o a t
TWOPI
=
2 . 0 f P I ;
/ /
360
d e g r e e s
c o n s t
f l o a t
PIOVERTWO
=
P I / 2 . 0 f ;
/ /
90
d e g r e e s
/ /
Compute
r a d i a l
d i s t a n c e
r
=
s q r t ( x x
+
y y
+
z z ) ;
/ /
Check
i f
we
a r e
e x a c t l y
a t
t h e
o r i g i n
i f
( r > 0 . 0 f )
{
/ /
Compute
p i t c h
p i t c h
=
a s i n ( y / r ) ;
Search WWH ::




Custom Search