Creating homing missiles
Now that our enemies are a bit stronger, let’s add the ability for our player to have some safety method to be able to kill our enemies without having the stand in front of them. We are going to only allow a certain amount of missiles the be stored by the player at a time, and as to how they are received, we will create a quick powerup that spawns at a very rare rate.
To start, we are going to create our missile prefab in the inspector and add in the appropriate components along with a recoloured version of our thrusters:
From here, we are going to attach a new script to our missile to give it it’s proper behaviour:
For our homing missile script, there is a lot in there, and a bunch of newer code implementations. In our Void start, we are just implementing a basic behavior in which we are telling our missile what tags we want to look for.
Next up, in our update, we are going to set up the meat of our homing missile code. To start, we are telling the missile that we want it to Move Towards our enemy units in a direction towards our closest enemy. The next part is for our prefab of the missile to rotate in line with it’s path towards the target, so it looks like an actual missile seeking the enemy, and not a stick awkwardly moving towards the enemy. For mathf, these functions are used in Unity to perform various calculations to determine the criteria in which you are searching for:
The next part of our missile script is just telling it to move upwards if there is no enemy target, and once it is off the screen, we want to destroy the missile.
The last part of our script is the FindEnemy void. This one is used to look for the enemy and determine the distance it is from the enemy along with where it needs to travel to so that it seeks out our target.
Next, we will need to go into our player script and create a firing method for the missile to work from:
As with our ammo mechanism, that we worked on here, we are going to have a limited amount of missiles to fire off. As for the replenishing of our missiles, we will use a new powerup, but because this is such an effective firing method, we are going to give it a very low chance at spawning for us to collect. Once we repeat the process we took to make the missile powerup work the same way as our ammo powerup, we can move to our game and see how it all looks:
Now that we have a working missile system in place, we can move on towards the last couple steps of our game.