###### Learn to Code Space Invaders – Lesson 25 – Level Up!

17th November 2019###### Learn to Code Asteroids – Lesson 2 – Moving With Vectors

19th December 2019# Asteroids Lesson 1 – Drawing Vector Shapes

Asteroids uses a very different way of drawing the game objects on the screen. Instead of using bitmap sprites, each of the game objects is drawn as a series of lines. This is called vector graphics.

I’ve purposely chosen a game based on vector graphics to give us an extra challenge in developing our software. We’ll have to work out a way to model, draw and move our player ship, asteroids and any other game items in our code without the luxury of any built-in functions that will render or rotate or animate them for us.

In this lesson we’ll design our data objects so we can model vector shapes as a series of points. We’ll then write some code that will turn this point information into a series of lines that we can then draw on the screen. At this point will be able to define a shape such as a player ship and render it at any position on the screen. But we also need to be able to rotate the ship so that it can point in any direction.

To rotate our shape will need to use a little bit of mathematics to give us an equation that lets us take the coordinates of a point and rotate them by a known angle around the origin. The equation will be using is shown in the diagram below.

To fit this into our code will need to write a special function that accepts two parameters. One will be the coordinates of the point we want to rotate. The other will be the angle we need to rotate it by. This function will then return us an object containing the new X and Y coordinates of our rotated point.

Once we got this code running we’ll test it by adding the left and right rotation keys into our code and hooking them up so that we can press them to rotate the vector graphic of our player ship.

As we go through the lesson I’ll explain the theory behind each part of our code but then give you the chance to write your own solution. Simply pause the video, have a go for yourself and then restart the video so they can take you through my solution on screen.

All the source code for the finished version of this lesson is available below.