HTML and CSS Reference
//ConsoleLog.log(e.keyCode + "up");
keyPressList[e.keyCode] = false;
<div style="position: absolute; top: 50px; left: 50px;">
<canvas id="canvas" width="200" height="200">
Your browser does not support HTML5 Canvas.
Once this file is run in a browser, you should be able to press the left and right keys to
rotate the ship on its center axis. If you press the up key, the ship will move in the
direction it is facing.
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 2 pixels per frame. It's easy to calculate
the current velocity if we are only moving in 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
var movingXNew = movingX+thrustAcceleration*facingX;
var movingYNew = movingY+thrustAcceleration*facingY;