Game Development Reference
In-Depth Information
130 float DistanceFromPlayer = Vector3.Distance(ThisTransform.position,
PlayerTransform.position);
131
132 //If outside chase range, then revert to patrol state
133 if(DistanceFromPlayer > ChaseDistance) {ChangeState(ENEMY_STATE.PATROL);
yield break;}
134
135 //If outsideattack range, then change to chase state
136 if(DistanceFromPlayer > AttackDistance) {ChangeState(ENEMY_STATE.CHASE);
yield break;}
137
138 yield return null;
139 }
140 }
141 //------------------------------------------------
142 }
Lines 25 and 28 . Here we defined some distances (measured in Unity units ) for
the Chase and Attack behaviors. When chasing, the ChaseDistance is critical
in determining whether the Enemy should switch to the patrolling or attacking
state. When attacking, the AttackDistance determines whether the Enemy
should switch back to the Chase state.
Line 48 . The ChangeState function is responsible for switching or moving the
state machine from one state to another. When a state-changing condition in
the system is detected (such as when the Enemy enters the AttackDistance
from the Player), the ChangeState function must be called to change states.
Lines 56, 84, and 103 . The coroutines AI_Patrol , AI_Chase , and AI_Attack are
looping routines that repeat for as long as the enemy is in the respective state.
In essence, these functions handle all frame-based functionality for a state.
Note Right now the states do not perform all the needed behavior. For example, the Chase state will not
(yet) make the Enemy actually chase the Player. This will be implemented in coming sections.
Preparing for State Implementation
In the previous section, we coded the main logic governing the enemy FSM. This included all its
states (Patrol, Chase, and Attack), all of which are controlled through specific coroutines in the
class. And finally, we implemented a function ( ChangeState ) to switch between states whenever the
appropriate conditions arise during gameplay; and generally, these conditions relate to the amount
of distance between the Enemy and the Player at any time. Together, this functionality represents
the core of the enemy FSM, but so far the states are not “fleshed out.” The various states can
handle state switching, allowing us to immediately change from one state to another, but none of
them actually make the Enemy do anything else. The Chase state doesn't make the Enemy chase
the Player, the Patrol state doesn't make the Enemy patrol, and the Attack state doesn't make the
Enemy attack. So now it's time to implement these.
 
 
Search WWH ::




Custom Search