Giving the player a homing missile

Today, we will be creating a homing missile for the player to use against the enemies. First, find a sprite that you want to use for the missile, then add a BoxCollider2D on it and set it as a trigger. Then add a Rigidbody2d component and set the gravity scale to zero. You will also create a powerup for the missile just like we did all the other times before. We will need to prefab both of those game objects.

We’re going to create a new script for the homing missile and attach it to the missile prefab. In the new ‘HomingMissile’ script we will need to create a couple of variables.

We will start by writing the function to locate the closest enemy. We’re going to search an array of enemies and see which one will be the closest to the player. We will be using a try and catch technique for this function since we will most likely have exceptions to which enemy is the closest to the player, and if any enemies are even on the screen.

We will now create a function for the missile to move towards the enemy.

In our player script, we will need to create a couple of variables for the homing missile to work off of.

We will write a function to instantiate the homing missile and we will write a function that we will use for collecting the powerup.

We will need to remember to add a new case to the ‘Powerup’ script for this new missile powerup.

In the ‘Enemy’ script we need to add the collision output. This is a continuation of the laser and isShieldsActive = false statement.

Now you should have a working homing missile for the player.