Creating a Homing Projectile in Unity (Part 1/2)

More cool weapons

Rusben Guzman
2 min readAug 31, 2021

Objective: create a new laser type that follow the closest enemy

The first step was to duplicate the laser prefab and create a new script called Homming_Laser.

In the homing laser script I declared some variables. A transform (_nearestEnemy) to store the closest enemy reference, and auxiliary (_minDistance), the speed of the projectile and the rotation speed.

So to find the nearest enemy we have to get all enemies and compare the distance with each one and just store the enemy with the lowest distance.

To implement the pseudocode I used a foreach loop and to get all enemies I use the function FindGameObjectsWithTag(“Enemy”) and a simple if statement to check if the current enemy distance is lower than the _minDistance.

To make the laser follow the enemy in the update method I used the function Vector3.MoveTowards() and passed as parameters the transform of the laser as a source, the transfor of the nearest enemy as a target and the speed multiplied by Time.deltaTime. Also to give a cool animation I added the function Transform.Rotate() and passed as a parameter the rotation speed by Time.deltaTime.

And that’s all that we need to create the homing laser prefab. In the next article I’m gonna create the pickup prefab and activate the homing projectile from the powerup script.

--

--

Rusben Guzman
Rusben Guzman

Written by Rusben Guzman

A Software Engineer passionate about game dev and interactive products with Unity. I consider video games to be the artistic expression of programming.

No responses yet