Game Development Reference
In-Depth Information
Line 13 . Here we draw an imaginary circle or area around the Enemy character,
and randomly pick a point inside it within the scene. This process is about
choosing a random new location to act as the destination for traveling.
Lines 19 and 20 . The problem with picking a random location inside the
level is that we don't know where the location will be. This entails risk. For
example, it's possible the Enemy could be standing close to a wall and that
we randomly pick a point behind the wall , perhaps a location that's impossible
to ever reach because it's outside the navigation mesh and area of the level in
general. In this case, the destination is indeed random , but it's unreachable in
all possible scenarios. To avoid this problem, we can use the function
NavMesh.SamplePosition to validate our random destination before traveling
there. This function will give us the nearest valid position on the navigation mesh
to our specified destination, if the original destination is not valid.
Line 23 . Here we set the agent destination in script. When we do this, the
NavMeshAgent will automatically travel there, avoiding obstacles and observing
the topology of the NavMesh.
Lines 26-51 . Being able to send the NavMeshAgent toward a destination is
great. But, how do we know when it's arrived there? It's important to know
this because, when it arrives, we'll need to pick a new and random destination
elsewhere to travel toward. Currently in Unity, there's no function to answer this
query directly; we must code our own functionality to determine destination
arrival. We do this at line 35. You might wonder why we can't simply compare
the Enemy position directly to the destination to see whether he's arrived, such
as enemy.position == destination.position . The reason relates to floating-point
precision on computers due to rounding issues and large number storage.
In practice, it may be that two objects are (to the eye) at the same location
in the scene, even though their world positions (expressed in floating-point
numbers) are fractionally different, mathematically speaking. This makes direct
comparison troublesome when attempting to assess equality, and so often, two
objects that appear to be in the same position actually have slightly different
positional values. So, instead we can use an Epsilon and a Timeout . The Epsilon
means that if the Enemy arrives within a certain distance of the destination
( ArrivalDistance ), then we'll classify the destination as reached. The Timeout
technique is used as a fail-safe feature, in case any inaccuracies or slip-ups
occur during the pathfinding process (which is possible, in practice). This means
that, if a specified time has elapsed since travel began ( TimeOut ), then pick a
new destination, as though the Enemy had arrived (see Figure 7-15 ).
Search WWH ::




Custom Search