State Machines

This page will contain downloadable C++ source code for finite state machines, suitable for use in computer games, simulation and related applications. A state machine is defined in an XML file, allowing designers to drive behaviour without the use of full-featured scripting languages. Despite this, state machines can invoke functions in the supporting application through the use of a lookup table.


The simulation module operates in two modes:

  1. discrete timesteps, and;
  2. interrupts.

The XML file allows you to invoke functions for states/transitions at various times/events, depending on the mode of operation. An arbitrary number of functions can be invoked upon an event, which can take one of the following types:

  • on state entry
  • on state exit
  • on update
  • on transition

For instance, you could use the state machine library to design a simple agent that switches from an ‘idle’ state to an ‘alert’ state when a noise is made in its environment. Upon entering this state, a function could be used to have the agent make a particular sound, or exhibit a particular facial expression.

The method for implementing functions is simple: the software allows you to register C/C++ function pointers¬†in a lookup structure (dictionary); if a state machine needs to fire a function named X, it looks for “X” in the¬†dictionary, firing it if the function is found.


The following example shows the beginning of a finite state machine for a computer game enemy. It starts in an idle state, in which it just sits there activating an idle animation. (We isolated the motion of the agents through the use of intermediate behaviours). Each update tick, the agent will ask its sensory mechanism whether there is a player within its visual field. If it does spot the player, it switches to another state. Eventually, it ends up targeting the player, entering a ‘tracking’ state if the player is within a certain range. If the agent is close enough to the player, it will launch an attack.

XML excerpt

Sample Code 1

The astute reader will also notice transitions that are not associated with a state. These are global transitions, defined for convenience. In this case, if the agent gets hit by an object, it enters a ‘get hit’ state. Our physics engine would generate events of this nature automatically. Likewise, it is often convenient to be able to kill an agent off instantly, for purposes of gameplay. The ‘die’ transition accomplishes this goal, from any state.

Comments are closed.