Objective: Create a Player fired missile that will hunt down and destroy the closest enemy.
The powerup itself will work the same way all the other powerups work and will be added to the modular powerup system I created Here.
I also decided to use a separate ammo system for my missiles the same way I created an ammo system for the Player’s laser weapon Here.
Create the missile sprite and attach a new script to the prefab called Player_Missile:
Open up the new Player_Miisile script to begin to implement the behavior for the missiles.
We will need five variables for getting the homing missiles to work:
- _target will be anything we assign the Enemy tag to.
- _noTarget will be if no enemies are on the screen the missile will fly in a straight line.
- _rigidBody a reference to the game object's rigidBoby2D.
- _angleChangingSpeed will be how fast the missiles will turn.
- _moveSpeed is the speed the missiles will fly at.
Now go ahead and assign all the values in the Unity Inspector:
Now we can begin to create the code to allow for the missile to find and fly towards enemies:
This is an easy way to get an object to home in on another object but one problem with how it is currently set up is the missiles will only track the first enemy created. We need to have the missiles target the closest enemy to them for more realism:
Now the missiles will track nearby enemies and not the first one created. Now we can tell the missile what to do if no enemies are on the screen and tell the missiles to destroy themselves if they get too far:
The last thing to do is in the Enemy script to have the enemies change their tags from Enemy to Dead_Enemy so the missiles don’t track the enemies while they are in their death animations: