Selecting Nearest Target
So yesterday, We made a tracking Missile. That’s good but how do we actually set a target for our new Missile. When it is being used by the Enemies against the Player it is simple. There is only the one Player, target them, but there are many targets for the Player to choose from. So, Let’s target the closest enemy…
Here is the method we use to get the closest target. There is a lot going on here, so let’s break down.
We need some variables to hold stuff as we work through the problem of finding the Closet Target. First is an Array that holds all our targets. Next is a place to hold our current ClosestTarget, this will change as we work through the Array. Then we have Floats for the current Distance and one for the current Closest Distance, MinDist.
The next line is how we find all the targets. Since this is the Player looking for targets, we use the Tag “Enemy” to identify those targets. If we have been properly tagging our different Enemy types with the “Enemy” tag, then they will show up in the list.
Now we get into the Meat of the problem. Using a For Loop, we cycle through each Target in our Array. We get the Distance between the Player and Target by using the Vector3.Distance function. If the Distance is closer than our closest Distance, it becomes the closest distance and the Target becomes the ClosestTarget.
And Finally, once we have gone through the list, we return the ClosestTarget so that we can assign it to the Missile.