Phase 2: Homing Missile
Objective: Create a new powerup that gives the user a single homing missile that targets and destroys the closest enemy
At this point we know the story, new powerup means a new collectable with an animation first then add that to the spawn manager and adjust the probability of spawning then set an isActive bool on the player along with a method called from the powerup script to activate it.
We will start stright into the Missile. Create a prefab add a rigidbody and collider and set the usual trigger and no gravity. Next create a Missile script and attach it to the Missile prefab. Create a float for missile speed, A GameObject array for the enemies, a transform for the target, two floats for distance too and closest enemy. Finally we need a quaternion for the target rotation.
Firstly we need to get the enemies so using a gameobject that find objects with tag we set the array in the update method. Next we create a SetTarget method and create two Vector3, one for missile position and one for enemy position not assigned yet. We then use a foreach loop to get each enemy. If the target is null which it will be on first enemy run, we set the target as the first enemy.transform, the enemy position to the target postion, the target rotation, the distance between the missile and enemy and set closest enemy as this enemy.
We then run through the rest of the enemies and the only difference here is checking if the current set target distance is closer and if not set the enemy as the new closest. Once this is all done we set the transform of the missile using a Vector3. MoveTowards and set the rotation of the missile using a Quaternion.Slerp to have it point at the enemy. We also set a coroutine so that the missile is destroyed if it doesnt hit a target within a given time.
Next in the player script we create the missile gameobject, missile active bool, audioclip for no enemies and the enemies gameobject array. Like in the missile we assign the array in the Update method. We are assigning key M for missile so we run an if key check in the update. Inside this we check if missile is active or else play the empty ammo sound. If active we check that the enemies array length is 1 or more. If less then play the no enemies sound and if 1 or more we call the FireMissile method which instantiates the missile and sets is active to false. Because the Missile will be rare and the enemies can now shoot backwards, dodge and have other improvements the missile will not be effected by shields and so on and will destroy the target enemy.
In the next post, we will finish off the game logic by creating a boss enemy within a final wave.