HTML and CSS Reference
In-Depth Information
angles, but we still need to convert our 45-degree angle into radians. We do that with
a standard formula: radians = angle * Math.PI/ 180 . And in the code:
var angle = 45;
var radians = angle * Math.PI/ 180;
Before we can discuss how we calculate the movement of our object along our vector,
we need to review a couple trigonometric concepts. These are cosine and sine , and
both relate to the arc created by our angle (now converted to radians ), if it was drawn
outward from the center of the circle.
cosine
The angle measured counterclockwise from the x-axis ( x )
sine
The vertical coordinate of the arc endpoint ( y )
You can see how these values relate to a 45-degree angle in Figure 5-2 .
Figure 5-2. Angles on the canvas
This might seem complicated, but there is a very simple way to think about it: cosine
usually deals with the x value, and sine usually deals with the y value. We can use sine
and cosine to help us calculate movement along our vector.
To calculate the number of pixels to move our object on each call to drawScreen()
( xunits and yunits ), we use the radians (direction) we calculated and speed (magni-
tude), along with the Math.cos() (cosine) and Math.sin() (sine) functions of the Java-
Script Math object:
var xunits = Math.cos(radians) * speed;
var yunits = Math.sin(radians) * speed;

Search WWH ::

Custom Search