Finite State Machines with Unity3D – Part 1

fsm2

The state pattern is an easy way to structure code in-game programming since most of the games mesh well with the idea of states and transitions. This pattern is often implemented as a finite state machine, being finite the number of states.

Let’s see a simple example:

fsm1

This simple state machine defines the behavior of a, rather dumb, enemy entity. We can differentiate states in which the enemy will be (one and only one at any given time) and conditions that will trigger state changes (transitions).

If we put the diagram into code, we could end with something like this:

As you can see states are well-defined, and each state will check for conditions to change state. More importantly, the code reads well, always aim for thin states, and extract code related to the logic that drives the behavior implementation into other classes when possible.

A clean code state machine should be about giving orders and choosing when to change state.

But even if you try to keep states as thin as possible it’s obvious that, unless you are doing something very simple, it’s going to be necessary refactoring states to separate classes and building a system that can manage these states into a well-structured state machine.

In the next post I’ll introduce a finite state machine based in the implementation found in Mat Buckland’s book Programming Game AI by Example and we will see how to go even further with hierarchical state machines.

Tags:

Acerca de

Ver todas las entradas de