HTML and CSS Reference
In-Depth Information
var
var
dx
=
p2
.
x
-
p1
.
x
;
var
var
dy
=
p2
.
y
-
p1
.
y
;
To determine the
distance
value, 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
var
distance
=
Math
.
sqrt
(
dx
*
dx
+
dy
*
dy
);
Next, we need to use that calculated
distance
value 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
(callsto
drawScreen()
)itwilltaketheobjecttomoveatthegivenvalueof
speed
.We
get this by dividing the
distance
by the
speed
:
var
var
moves
=
distance
/
speed
;
Thenwefindthedistancetomoveboth
x
and
y
oneachcallto
drawScreen()
.Wenamethese
variables
xunits
and
yunits
:
var
var
xunits
=
(
p2
.
x
-
p1
.
x
)
/
moves
;
var
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
var
ball
=
{
x
:
p1
.
x
,
y
:
p1
.
y
};
And create the interval to call
drawScreen()
every 33 milliseconds:
function
function
gameLoop
() {
window
.
setTimeout
(
gameLoop
,
20
);
drawScreen
()
}
gameLoop
();
Drawing the ball
Let'sdrawtheballonthescreen.Inthe
drawScreen()
function,wefirstchecktoseewhether
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
:
iif
(
moves
>
0
) {
moves
--
;
ball
.
x
+=
xunits
;
ball
.
y
+=
yunits
;
}