3D Game Programming

(C. Jardin) #1
In JavaScript, pi is called Math.PI. So 360° would be 2*Math.PI. A handy conversion
table follows:

Degrees Radians JavaScript
0° 0 0
45° pi ÷ 4 Math.PI/4
90° pi ÷ 2 Math.PI/2
180° pi Math.PI
360° 2 × pi 2*Math.PI
720° 4 × pi 4*Math.PI

Geometric functions are also available in JavaScript’s Math module. An
example is the sine that we saw in Chapter 6, Project: Moving Hands and Feet,
on page 59. JavaScript shortens both sine and its companion, cosine, to sin
and cos:

Math.sin(0);
// 0

Math.sin(2*Math.PI);
// 0

Math.cos(0);
// 1

Really, Really Close to Zero
Depending on your computer, when you tried Math.sin(2*Math.PI) in
the JavaScript console, you may not have gotten the right answer.
The sine of 2 × pi is zero, but you may have seen something like
-2.4492127076447545e-16 instead. This shows that computers are not
perfect. Sometimes their math can be off by a tiny amount.

When JavaScript has e-16 at the end of number, it means that it’s
a decimal number with the 16 places to the left. In other words,
-2.45e-16 is the same thing as writing -0.000000000000000245. That is a
really, really small number—you would have to add it more than
two million times to get 1.

We won’t need these Math. functions often. They will pop up now and again
as we progress. For the most part, we can make do with the simple arithmetic
operators for addition, subtraction, multiplication, and division.

Chapter 7. A Closer Look at JavaScript Fundamentals • 72


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf