Skip to content

Why Canopy ​

A character in a combat game is rarely in one simple state. It is using a move, and that move is winding up. It is knocked back, and it is still flying. Some events apply to the whole group: being knocked back again interrupts any part of a move. Others apply to one part only: landing matters only while flying.

A flat state machine has to repeat the shared handlers on every state, or grow a state for every combination. Flags and timers spread the logic over the code that sets them. Canopy was built for attacks and AI that need deep states: each state sits inside the state it belongs to, and an event goes from the innermost state outwards until one handles it.

When to use it ​

Canopy is worth using when:

  • States group naturally, such as the phases of a move inside usingMove, or chasing and attacking inside fighting.
  • Several states share handlers, which belong on their superstate instead of being copied.
  • States end on a timer, such as a stun, a wind-up, or a rest with a random length.
  • Many owners, such as every enemy in a server, share one design but keep their own state.
  • You want the analyzer to catch a misspelt state or event before the game runs.

When something simpler is enough ​

  • A value with no states to name, such as a counter or a health value, needs no machine.
  • Two or three states with no nesting and no timers are often clearer as one variable and an if.
  • A one-off sequence, such as a cutscene that always plays in the same order, may read better as a script that waits.

Compared to writing it by hand ​

By handWith Canopy
Copy the handler for a shared event onto every state that needs itPut it once on the superstate, and every child passes the event up to it
Keep a timer per state and check it every frameGive the state a duration and handle onTimeUp
Remember to reset a state's variables each time it startsIts memory is made fresh on each entry
Work out which cleanup to run when jumping between distant statesA move leaves exactly the states it no longer needs, innermost first
Find a misspelt state name when the game misbehavesThe analyzer reports it in your editor
Fake the time in tests by waitingPass any time to process