27 · AI · 2D and 3D

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.

←→ moveF or Space attackM state machine / flags◀ ▶ move, tap the scene to attack

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.

State PatrolImpossible combos 0

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.

42 words · one sentence to paste as is

Where it's used

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.

Related concepts

New concepts, in your inbox.

One short email when we add new concepts, plus our weekly roundup of AI tools for game devs. Unsubscribe any time.