Giving the Player Ship a Maximum Velocity
If you play with the code in Example 8-8, you will notice two problems:
The ship can go off the sides of the screen and get lost.
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
value will always be 0
. The current velocity we are moving on one
axis would be 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
maxVelocity
=
2
;
Next, we must make sure to calculate and compare the maxVelocity
to the current velocity
before we calculate the new movingX
and movingY
values. We will do this with local
variables used to store the new values for movingX
and movingY
before they are applied:
var
movingXNew
=
movingX
+
thrustAcceleration
*
facingX
;
var
movingYNew
=
movingY
+
thrustAcceleration
*
facingY
;
The current velocity of our ship is the square root of movingXNew^2 ...
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.