ZX Spectrum Jetpac – Retro Game Deconstruction
12th January 2020Learn to Code Asteroids – Lesson 6 – Polygon on Polygon Collision Detection
17th January 2020Learn to Code Asteroids – Lesson 5 – Scaling Vector Graphics
In the previous lesson we managed to get our point in polygon collision detection working so that we can now detect when one of the player bullets hits an asteroid. But at the moment our asteroid explosion function simply removes the hit asteroid from the asteroids array and then removes it from the screen. In our final version we need to be able to split large asteroids into two medium-sized asteroids, and when those are hit they will split into two small asteroids, and when those are hit they will finally be destroyed.
To get this working we need to be able to create asteroids at different sizes. We already have a block of code which can generate a random vector asteroid so we want to be able to slightly modify this by using a scaling factor.
Our scaling factor will be a number we give to the asteroid generating code so that as it is generating points around the circumference of the asteroid it will make them bigger or smaller. If we remember back to how we generate the asteroids we divided a circle into a number of segments and then place points at random distances from the centre along each of the radii created by the segments. Our scaling factor will simply take these random distances and divide them to make them smaller. Therefore a scaling factor of one will divide the radius by one living at the same. A scaling factor of two will have the distance and a scaling factor of four will quarter the distance. This will give us our three different sized asteroids.
Our software needs to know what size each asteroid was created as. When we explode asteroids will get a different number of points depending on the asteroid size and will also have to detect when the asteroid is the smaller size so that we can destroy it rather than divided into two parts. This needs us to store an extra tribute inside the asteroid object definition which will keep track of the scaling factor used to generate that asteroid.
Once we got the logic working we can add the scoring system into the game and create a sound effect for the asteroid explosions. To display the score on the game screen will need an extra drawing function for the game information. At the moment this will only display the player score but eventually it will display how many lives the player has left and perhaps a high score. By breaking this out into its own special function now will make adding extra bits easier in the future.
The full code for this lesson is available below.