State machines for game characters and AI explained
A finite state machine (FSM) is one of the most useful patterns in game programming. It's a way to organize behavior so a character is always in exactly one clearly defined state.
The idea
A character might have states like:
- Idle
- Walking
- Jumping
- Attacking
- Stunned
Each state handles its own logic, and transitions define when it moves to another state (for example, "jump pressed while grounded" moves from Walking to Jumping).
Why it helps
Without a state machine, code often becomes a tangle of booleans: isJumping, isAttacking, isStunned. Then bugs appear when two are true at the same time. An FSM makes impossible combinations impossible.
Basic structure
- Each state has enter, update and exit methods.
- The machine holds the current state and calls its update every frame.
- When a transition triggers, call exit on the old state and enter on the new one.
Common uses
- Player controllers
- Enemy AI (patrol, chase, attack, flee)
- Game flow (menu, playing, paused, game over)
- Animation (most engines' animators are state machines)
When it gets complicated
- Hierarchical state machines group related states (e.g. "grounded" containing idle, walk and run).
- Behavior trees are often preferred for complex AI with many decisions.
- Utility AI scores options and picks the best one.
Do you use state machines in your projects, or something like behavior trees? At what point did an FSM start getting too messy for you?
Comments · 3
This is clearer than the tutorial I tried before. An enum plus a switch is basically what I was missing, right?
Once you have more than a handful of states, look at behaviour trees. State machines get messy when transitions multiply.
Classic example: the enemy that patrols, chases, then gives up. Simple and it feels alive when it's tuned well.