Canvas Basics - Moving Rocket Ship

In the second tutorial we looked at keyboard input. The problem with the keyboard input, that we looked at, was that it didn’t really translate into a real game mechanic. So in this tutorial we’ll look at making a space craft, similar to that found in the old arcade game, Asteroids.

The code is available from here. The example page showing the code in action can be found here.


The player.js replaces Square.js from our previous tutorials. There are two significant parts to this. The first is how the triangular space ship is actually drawn and the other is how to move forwards and backwards.

How to draw the space ship

Much as in the first tutorial we have to draw everything based on points calculated on a circle around the object. This is to make it possible to rotate the object later on. Observation of the code should explain how these points are generated. (The code is inside the player.js playerDraw() function).

Moving the object forwards

As you can probably imagine we cannot simply add a number to the x and y directions as we have done in the previous tutorial. The movement of the object should depend on the rotation and should be a uniform speed in any direction. We achieve this by calling through to one of the helper functions available within FiltoidMaths.js, called MoveForward(rot,amount). The rotation is the value in radians of the rotation and the amount is the amount by which we want to move. What is returned is the translation which we must apply to our object. This means that you must add the returned values of x and y (it returns a Location) to the current location of the object which has called the function to make the movement as expected.