State by

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

Motivation

In games the finite state machines(FSM) has a number of various uses. For example characters in games often have a finite numberof animations and a number of transitions in between those animations. A character may be able to crouch while standing up, but not while jumping or falling. So a character in standing state would be playing the idle standing animation and the state transitions might allow character to go into jumping, walking or crouching state. Upon entering a new state the animation would be swapped. Although the actual implementation is often somewhat more complex, as we also want to be able to blend two or more animations together during a transition, have one set of states for characters legs, while another set controls the hands and all that while inverse kinematics is taking care of the head rotation.

Some other uses for FSMs in games could be:

  • AI decision making - should the guard be searching, attacking or running away?

  • The in game UI/menu states - are we currently displaying settings, save games or main menu?

  • Application states - is the game paused, loading a level or saving?;

  • Environment states - is a door open, closed, currently being lock picked or broken?

Essentially if behavior of a class depends on a number of flags, which change based on input or events and can not be true at the same time, then it is a good place to consider using a finite state machine.

The state pattern helps us implement a FSM in object oriented fashion. The pattern encapsulates each state into different sibling class. Each class knows how to handle its own behavior and to transition into another state, we change the reference field to an object of another class.

The state chapter in Game Programming Patterns delivers code examples for different variations on implementation and also introduces hierarchical state machines, concurrent state machines and pushdown automata.

Structure



Example Uses

Use a finite state machine when:

  • You have an entity whose behavior changes based on some internal state.

  • That state can be rigidly divided into one of a relatively small number of distinct options.

  • The entity responds to a series of inputs or events over time.

 

;