Game Development Reference
In-Depth Information
The following are the comments for code sample 7-6:
•
Line 12
: Here, the
Random.Range
function selects a random destination
from the
Waypoints
array. This is passed as a destination argument to the
SetDestination
function of the
NavMeshAgent
component that sends the
enemy to the destination.
•
Line 28
: The function
Vector3.Distance
is used to determine whether
the agent has reached the destination. This does not check for equality
between the enemy position and destination position, because floating-point
inaccuracy means we cannot guarantee that the two will ever be the same.
Instead, it checks whether the enemy has come within a specified distance
of the destination (
DistEps
), classifying that as having arrived.
•
Line 32
: If the destination is reached, the enemy would return to
Idle
. After
waiting for one cycle of the idle animation, the enemy would again enter into
the
Patrol
state.
•
Line 21
: Again, the
Patrol
state depends on whether the player is visible to
the enemy. If so, they enter the
Chase
state.
The Boolean variable
CanSeePlayer
indicates, for any frame, whether the player is
currently visible to the enemy. This variable is updated on each frame. The process
for this begins inside the
Update
function, as shown in the following code sample 7-7:
01 void Update()
02 {
03 //Assume we cannot see player
04 CanSeePlayer = false;
05
06 //If player not inside bounds then exit
07 if(!ThisCollider.bounds.Contains(PlayerTransform.position)) return;
08
09 //Player is inside bounds, update line of sight
10 CanSeePlayer = HaveLineSightToPlayer(PlayerTransform);
11 }
The key question for the
Update
function is whether the player is inside the box
collider attached to the enemy; this box collider represents the enemy's view
or range. If the player is inside that box, the player could possibly be visible to
the enemy. In this case, further checks are required to be sure. This is where the
HaveLineSightToPlayer
function is essential. This function returns a Boolean
(
true
/
false
) value that indicates whether the player is visible to the enemy,
as shown in the following code sample 7-8: