Creating a Homing Projectile for our 2D Galaxy Shooter in Unity-Part 01!
Objective: To give the player a homing missile that destroys the closest enemy target.
Now it is time to give the player a Homing Missile feature that cycles through all the active enemies on the screen and detects which is the closest one and intercepts it and destroys it! We are going to be working on 2 scripts for this one and part 02 will cover the second script. Let’s jump into it…
Create a New Script “HomingMissile”
Let’s start with creating a couple variables that we are going to need:
Next, let’s look for our players Input when they press the ‘E’ key as this is going to be our hotkey for this feature:
Our first If check is going to be if the ‘E’ is pressed and whether the homing missile cooldown is not active. If so, then let’s instantiate a homing missile prefab at the player’s location.
Next, we need to grab the <HomingMissileBehaviour> script component that is attached to the homing missile so we can call a method from that script that is going to cycle through all the active enemies on the screen and determine which is the closest target. We should always be null checking that we are successfully using script communication. We are also going to start the HomingMissileCooldownRoutine() coroutine that is going to handle our timed event (10 second cooldown).
Lastly, let’s check to see if the ‘E’ key is pressed and whether the coroutine running is true, so that we can simply debug.log a message to the console for the time being until I create an on screen UI element.
Here is the coroutine as mentioned above:
The WaitForSeconds class could also be cached to prevent us using the ‘new’ keyword every 10 seconds and having multiple instances, when we only need 1!
Next Up: Part 02 — The second script is going to handle the homing missile behaviour