Game Development Reference
In-Depth Information
Finite State Machines (FSMs)
So let's start creating intelligent enemies (notice that I didn't say artificially intelligent)! The three
Enemy types for CMOD (the Drone, the Tough Guy, and Mr. Big Cheese) will all share the same
behavior; and so the intelligence will be coded into the Enemy base class, and not into any of
the derivatives—allowing all the derived classes to inherit the functionality. For CMOD, the three
Enemies will work as follows in terms of intelligence:
1.
When the level begins, all Enemies will wander or patrol around the
environment. They will continue doing this until they come close to the Player
and the Player enters their line of sight. That is, when the Player enters an
Enemy's observation radius .
2.
When the Player enters an Enemy's observation radius, the Enemy will
change its behavior. Specifically, it will stop patrolling, and will start pursuing
or chasing the Player.
3.
The Enemy will continue to chase the Player until either the Player leaves
the Enemy's observation radius (the Player outruns the Enemy), or when the
Enemy comes within attacking distance to the Player.
4.
If the Player leaves the Enemy's observation radius, the Enemy returns back
to a Patrol state, wandering the level repeatedly.
5.
If the Enemy enters attacking distance to the Player, the Enemy will change
behavior again. Specifically, he will change from chasing to attacking.
6.
When an Enemy is attacking the Player, he will continue to deal damage
using his weapon, until either the Player dies, or the Player is no longer within
attacking distance.
Together these conditions and this logic define the general intelligence pattern for the Enemy. This
kind of system is called a finite state machine , because the Enemy can be in only one state at any
one time (Patrol, Chase, or Attack), and all of these states are known in advance and are connected
to one another by relationships in a complete system. That is, the Enemy can change from any one
state to another, only when certain conditions happen. We may start to define the states for this
machine in the Enemy class using C# code with an enum , as shown in Listing 7-5.
Listing 7-5. Defining the States for an FSM
01 using UnityEngine;
02 using System.Collections;
03
04 public class Enemy : MonoBehaviour
05 {
06 //Enum of states for FSM
07 public enum ENEMY_STATE {PATROL = 0, CHASE = 1, ATTACK=2};
08
 
Search WWH ::




Custom Search