HTML and CSS Reference
In-Depth Information
To determine the
distance
, we square both the values we just created, add them, and
then use the
Math.sqrt()
function to get the square root of the number:
var distance = Math.sqrt(dx*dx + dy*dy);
Next, we need to use that calculated
distance
in a way that will allow us to move an
object a uniform number of pixels from
p1
to
p2
. The first thing we do is calculate how
many
moves
(calls to
drawScreen()
) it will take the object to move at the given value of
speed
. We get this by dividing the
distance
by the
speed
:
var moves = distance/speed;
Then we find the distance to move both
x
and
y
on each call to
drawScreen()
. We name
these variables
xunits
and
yunits
:
var xunits = (p2.x - p1.x)/moves;
var yunits = (p2.y - p1.y)/moves;
Finally, we create a dynamic object named
ball
that holds the
x
and
y
value of
p1
…
var ball = {x:p1.x, y:p1.y};
…and create the interval to call
drawScreen()
every 33 milliseconds:
setInterval(drawScreen, 33);
Drawing the ball
Let's draw the ball on the screen. In the
drawScreen()
function, we first check to see
whether the
moves
variable is greater than zero. If so, we are still supposed to move the
ball across the screen because we have not yet reached
p2
. We decrement moves
(
moves--
) and then update the
x
and
y
properties of the ball object by adding the
xunits
to
x
and
yunits
to
y
:
if (moves > 0 ) {
moves--;
ball.x += xunits;
ball.y += yunits;
}
Now that our
values
have been updated, we simply draw the ball at the
x
and
y
coor-
dinates specified by the
x
and
y
properties, and we are done…that is, until
drawScreen()
is called 33 milliseconds later:
context.fillStyle = "#000000";
context.beginPath();
context.arc(ball.x,ball.y,15,0,Math.PI*2,true);
context.closePath();
context.fill();