HTML and CSS Reference
In-Depth Information
Giving the Player Ship a Maximum Velocity
If you play with the code in
Example 8-8
, you will notice two problems:
1. The ship can go off the sides of the screen and get lost.
2. The ship has no maximum speed.
We'll resolve the first issue when we start to code the complete game, but for now, let's look
at how to apply a maximum velocity to our current movement code. Suppose we give our
player ship a maximum acceleration of two pixels per frame. It's easy to calculate the current
velocity if we are moving in only the four primary directions: up, down, right, left. When we
are moving left or right, the
movingY
value will always be
0
. If we are moving up or down,
the
movingX
valuewillalwaysbe
0
.Thecurrentvelocitywearemovingononeaxiswouldbe
easy to compare to the maximum velocity.
But in our game, we are almost always moving in the
x
and
y
directions at the same time. To
calculate the current velocity and compare it to a maximum velocity, we must use a bit more
math.
First, let's assume that we will add a maximum velocity variable to our game:
var
var
maxVelocity
=
2
;
Next, we must make sure to calculate and compare the
maxVelocity
to the current velocity
before
wecalculatethenew
movingX
and
movingY
values.Wewilldothiswithlocalvariables
used to store the new values for
movingX
and
movingY
before they are applied:
var
var
movingXNew
=
movingX
+
thrustAcceleration
*
facingX
;
var
var
movingYNew
=
movingY
+
thrustAcceleration
*
facingY
;
The current velocity of our ship is the square root of
movingXNew^2 + movingYNew^2
:
var
var
currentVelocity
=
Math
.
sqrt
((
movingXNew
*
movingXNew
)
+
(
movingYNew
*
movingYNew
));
If the
currentVelocity
is less than the
maxVelocity
, we set the
movingX
and
movingY
val-
ues:
iif
(
currentVelocity
<
maxVelocity
) {
movingX
=
movingXNew
;
movingY
=
movingYNew
;
}