HTML5 Canvas [149]
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
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.