Finite state machine
One state at a time, with clear rules for switching.
Enemies and characters built from a pile of true/false flags end up in impossible combinations, like attacking while stunned. A state machine says the character is in exactly one state, Patrol, Chase, Attack or Hurt, and lists exactly which events move it to which state. Bugs become visible and fixable.
Try this: Walk near the slime, hit it, and watch the state graph. Then switch to Flags and hit it during its wind-up: it attacks while hurt.
Walk toward the slime.
Prompt bit
Works for 2D or 3D in any engine (Unity, Unreal, Godot, web). Paste the short one for a quick fix, or the detailed one when you want it done properly.
Drive the enemy with a finite state machine: one current state (Patrol, Chase, Attack, Hurt) with enter, update and exit functions and an explicit transition list, and let Hurt interrupt any state for 0.4 s so stale attack flags can never fire.
Refactor the enemy (or player) logic into a finite state machine (2D or 3D, any engine). Define states as an enum or small classes, each with enter(), update(dt) and exit(). Keep exactly one currentState and change it only through changeState(next), which calls exit on the old state and enter on the new one and logs the transition in debug builds. Start with Idle, Patrol, Chase, Attack (wind-up 0.4 s, active, recovery), Hurt (0.4 s) and Dead. Write the transitions down: Patrol to Chase when the player is seen within 6 units, Chase to Attack within 1.5 units, Chase to Patrol when lost for 3 s, any state to Hurt on damage, any state to Dead at 0 health. Timers and per-state data reset in enter() so nothing leaks between states. Drive animations from state changes, not the other way round. When states start sharing a lot, nest them (a hierarchical state machine) or move to a behaviour tree. Add a debug label above the character showing the current state.
Where it's used
- Enemy AI: patrol, chase, attack, flee in 2D and 3D
- Player controllers: idle, run, jump, fall, wall-slide, dash
- Animation systems: engine animators are state machines too
- Game flow: menu, playing, paused, game over
- UI and dialogue: step-by-step screens and conversations
Common mistakes
Using several booleans instead of one state (impossible combinations), changing state from many places without exit and enter, timers that carry over from the previous state, and one giant switch statement that grows forever instead of separate states.
Writing this with an AI assistant? See our best AI coding assistants for game developers.
Missing a concept? Request one.



