Creating a Homing Projectile for our 2D Galaxy Shooter in Unity-Part 02!

Chris Hilton
3 min readSep 3, 2021

--

Objective: The follow up to part 01 that gives the player a homing missile to destroy the closest target.

Create a New Script “HomingMissileBehaviour”

Let’s create a few variables that are going to handle the homing missiles speed; a bool trigger for our homing missiles movement and; an Enemy type variable that is going to store our reference to the closest enemy once it has been found.

Now we are going to have 2 different types of movement for missile. The first is going to check If an enemy target has been found and if so, then the missile is going to move towards that target.

Secondly, if the missile doesn’t find any enemy target, then it is simply going to move up the screen until it reaches 6 on the Y-axis, at which stage it is going to destroy itself. Bad luck, should have waited until there was an enemy on the screen!

This method is going to handle finding the closest enemy target (if any) and is called from the “HomingMissile” script when the missile is instantiated.

Next we need to create our variable that we are going to compare the enemies distances (_closestDistanceToEnemy) using Mathf.Infinity. We are also going to cycle through all active game objects in the scene ObjectsOfType<Enemy> and store the result in an array.

Next step is to null check whether we have found any enemies and if we have we are going trigger our bool so the missiles movement is now being directed towards a target.

Now we are going to dive into our Foreach loop and grab all the enemies distances that have been found (using sqr.magnitude) and then complete an If check against our Mathf.Inifnity variable, to find the closest one to the missile. Once found we are then going to set this enemy to our initial Enemy _closestEnemy variable we created at the start.

Don’t forget to also check for the array being equal to null, so we can debug any future issues.

This method is going to handle the movement towards the enemy target. Firstly, we need to set the direction as our current position less the enemy targets position.

Secondly, we are going to normalize our direction to set the maximum length of the magnitude to 1. This is going to stop our missile moving faster while it is moving at an angle.

Thirdly, Quaternion.LookRotation() is going to set the front (nose) of the missile to face towards the enemy target.

Lastly, the missile is going to move in the direction specified at the missile’s speed in real time.

Voila! Hope you have enjoyed this one, it was quite a fun feature to implement

--

--