Game Development Reference
In-Depth Information
Listing 20:
Target following script of the rocket
The longest step in
TargetFollower
is the search algorithm we perform in
Start()
. This
algorithm gets all targets in the scene, stores them in the array
allTargets
, and searches
for the nearest target to the position where the rocket is created. Before searching for the
nearest target, it is important to make sure that there are targets in the scene, which we do
in line 14 by checking whether
allTargets.Length
is greater than zero. If there are targets in
the scene, we take the first one and store it in
nearest
. It is important to realize that arrays
have zero-based positions, which means that the first object in the array is located at the
position zero. We use
allTargets[0]
o access the first object in the array. Storing the first
element in
nearest
means that we consider it the nearest one, then we start to search for a
possible closer object.
FindObjectsOfType<Target>()
returns all objects in the scene, including hit objects which
are currently playing falling animation. However, it does not return the targets which have
already been destroyed and removed from the scene. In line 22, we make sure that the object
has not yet been hit before considering it a candidate target. If the target has not yet been
hit, we find the distance between its position and the position of the rocket and store it in
distance
(lines 24 through 28). Additionally, we find the distance between the rocket and
the nearest target and store it in
minDistance
(lines 32 through 35). If
distance
is less than
minDistance
, this means that the current target is closer to the rocket than the nearest object