Day 58: Homing Missile
Objective: Fire a Missile that will find the closest enemy and destroy it.
To start we will need to be able to find a target. We do this by searching the scene for objects with the tag of enemy and save it to an array. Then we go though all the arrays and get the difference in distance. Which ever is the closest will be selected as the target.
In our update we will check to see if the _selectedTarget is null or not. If it is try to find an enemy again and move in a forward direction. If not move toward the target.
Next will be checking the OnTriggerEnter2D, here we will check to see if we collided with an enemy. If we did call the enemies OnHit() function and Instantiate the explosion.
We will create the power up like we have done in the past. This time though in the Player script we will allow for only one fire of the missile. We do this by setting the bool _isHomingMissileActive to false after the missile has been Instantiated.
When creating the prefab, all the normal stuff will be needed. The HomingMissile Script, RigidBody2D with gravity set to zero, and BoxCollider2D with isTrigger selected.
This is a quick article on getting a homing missile to work. Thank you for reading! Have a wonderful day!