Game Development Reference
Programming an FSM is a case of providing an NPC with a state value that
represents its current behavior. Each state is accompanied by an event value
representing the status of that state. The event tells us if the NPC has just
entered that state, has been in the state for a while, or is exiting the state.
Keeping track of this is critical for coordinating NPC movements around the
environment and its animations. The FSM runs each game loop; therefore,
knowing where the NPC is within a state is important for updating its
status, the status of other game characters, and the environment.
For example, consider a Sim whose state changes to “take bath.” Before it
can take a bath, it needs to make its way to the bathroom, run the bath, get
undressed, and hop in the bath. This would happen on entering the state.
The state would then enter update mode where the Sim is sitting in the bath
washing itself, singing, blowing, bubbles, and so on. Once the Sim is clean, the
state transitions to the exit phase in which it gets out of the bath and redresses.
In pseudocode, the code might look something like that in Listing 5.8 .
Listing 5.8 Code for Simple Finite State Machine
if( state == “BATH”)
if (event == “ENTER”)
event = “UPDATE”;
else if (event == UPDATE)
event = “EXIT”;
else if (event == “EXIT”)
state = “IDLE”;
event = “ENTER”;