HTML and CSS Reference
In-Depth Information
Figure 5-4. Angle of incidence is equal to the angle of reflection
In the next section, we will create a series of examples using this rule to animate objects.
The first,
Example 5-4
, will simply allow a single ball to bounce off the edges of the
canvas.
Bouncing a Single Ball
In this first example, we will create a ball traveling on a vector. We will set the
speed
(magnitude) to
5
and the
angle
(direction) to
35
degrees. The rest of the variables are
identical to those in
Example 5-3
. We are still moving on a vector, but now we will test
to see whether the ball hits a “wall” (the edges of the canvas), in which case it will
bounce off, using the rule of the angle of reflection. One big change from the previous
vector example is the location in which we initialize the values for
radians
,
xunits
, and
yunits
. Instead of setting them up when we initialize the application in
canvasApp()
,
we save that for a call to a new function named
updateBall()
:
var speed = 5;
var p1 = {x:20,y:20};
var angle = 35;
var radians = 0;
var xunits = 0;
var yunits = 0;
var ball = {x:p1.x, y:p1.y};
updateBall();
The
updateBall()
function is called every time we set a new
angle
for the ball, because
we need to recalculate the
radians
and find new values for
xunits
and
yunits
. A new
angle
is generated when the app starts, as well as every time the ball bounces off a wall: