In tutorial 2 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 tutorial 3 we’ll look at making a space craft, similar to that found in Asteroids.
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.
There are many places that this code can be taken and I encourage people to take this code away, copy it, rename it, i don’t care. Feel free to use it and please feel free to leave a comment if there is something that you don’t understand. If anyone fancied writing full usage documentation or writing some new additions for the base libraries then please let me know and I will include them in this blog post of in the base code.