Online Book Reader

Home Category

HTML5 Canvas [149]

By Root 6532 0
will need to include code to look for true (or false) values in the keyPressList array, and use those values to apply game logic:

if (keyPressList[38]==true){

//thrust

var angleInRadians = player.rotation * Math.PI / 180;

facingX = Math.cos(angleInRadians);

facingY = Math.sin(angleInRadians);

movingX = movingX+thurstAcceleration*facingX;

movingY = movingY+thurstAcceleration*facingY;

}

if (keyPressList[37]==true) {

//rotate counterclockwise

rotation-=rotationalVelocity;

}

if (keyPressList[39]==true) {

//rotate clockwise

rotation+=rotationalVelocity;;

}

Let’s add this code to our current set of rotation examples and test it out. We have made some major changes, so Example 8-8 presents the entire HTML file once again.

Example 8-8. Controlling the player ship

CH8EX8: Ship Turn With Keys

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:

The ship can go off the sides of the screen and get lost.

The ship has no maximum speed.

Return Main Page Previous Page Next Page

®Online Book Reader