Game Development Reference
In-Depth Information
This code uses cached variables: ThisAnimator , ThisTransform ,
ThisAgent , and ThisCollider . This lets us retrieve immediate and
direct references to attached components at level startup, which saves
us from having to call C# property functions ( get and set ) every
time we need access to an object. Thus, This.Transform carries a
greater performance overhead than the optimized, cached variable,
ThisTransform .
Each state in the FSM will be coded as a separate Coroutine, one Coroutine per state.
The Coroutine will loop infinitely and exclusively as long as the state is active, defining
all behaviors for the enemy in that state. The primary job of the state machine is to
select and initiate the appropriate state under the correct conditions. Let's start by
creating the Idle state—the default or normal state for the enemy.
Creating the Idle state
The enemy object begins in the Idle state (a "doing nothing" state), which is
primarily transitional. In this state, the enemies stand where they are, playing the
idle animation. The state is entered once at scene startup, but we'll also return to it
when exiting some other states, as an intermediary step before moving onto a new
state. Effectively, in this state, the enemy should always play the idle animation
just once and then leave the state when the animation is completed. The enemy can
further move to the Patrol state automatically, where they begin searching the scene
for the player. This involves a two-step process. First, we'll need to start playing the
idle animation as the Idle state begins. Second, we'll need to be notified when the
idle animation has completed, to initiate a change to the Patrol state. Refer to the
following code sample 7-3 for the Idle state:
01 //--------------------------------------------------
02 //This coroutine runs when object is in idle state
03 public IEnumerator State_Idle()
04 {
05 //Set current state
06 CurrentState = AI_ENEMY_STATE.IDLE;
07
08 //Activate idle state with Mecanim
09 ThisAnimator.SetTrigger((int) AI_ENEMY_STATE.IDLE);
10
11 //Stop nav mesh agent movement
12 ThisAgent.Stop();
13
14 //Loop forever while in idle state
15 while(CurrentState == AI_ENEMY_STATE.IDLE)
 
Search WWH ::




Custom Search