In lesson 1 we built the software needed to model our vector graphics and draw our shapes at any position on the screen. we also added the code to rotate these shapes to any angle we wanted.
We’re now ready to get these vector graphics moving around the screen. To do this we’ll need to build a model of how objects move in our game. The best way to create these models is to base them as much as possible on the real world and then modify their behaviour to suit our game.
We want our player ship to have a rocket engine to provide thrust. This thrust will accelerate the ship in the direction it’s pointing in. We’ll also be able to rotate the ship as it’s moving and then thrust in a different direction so we need to model how this new thrust direction changes the existing movement of the ship – just like a real space craft!
Our code is going to have to model motion using velocities as vectors (just like in your Physics class!) with a magnitude and direction. When we hit the thrust button our code will have to add the thrust vector to the movement vector to find the resultant velocity vector. This will need a number of functions to add and handle our vector quantities. I’ll be taking you through the theory but I’d like you have have a go at writing the code before I take you through my solution.
We’ll be learning how to define our velocities as vectors, how to split them up into horizontal and vertical components and then how to use these to model the ship movement. We’ll then develop our vector addition function to create the engine thrust in any direction the ship points. We’ll finish by creating the iconic screen wrap around effect used in the real asteroids games.
The full code for this lesson is available below.