A few years ago I wrote about the state machine I built for enemies in my game The Lost Card. At the end I said I wanted to learn how behavior trees work. I finally did (actually over a year ago now!), and it turns out my old system was most of the way there already.
A quick recap (read the old post if you want the full context): every enemy has a current state, which is just a string. When the state changes, the enemy’s constructNewBehaviorFor() method builds a Behavior object for it. The behavior runs until it’s done, then calls a callback to move to the next state.
That worked well for simple loops like “wait, then chase the player.” It got awkward for anything with branching logic. If a boss should do one attack on odd turns and another on even turns, or explode only when the player is close, every branch needed its own named state. The switch statements grew, and the logic for one attack got scattered across several case blocks.
Behavior trees neatly fix that. Here’s what they are and how I added them to the game incrementally without throwing out the old system.
What a behavior tree is
If you know this already, you can skip this part, but it was really cool when I figured it out so I want to make sure there’s something here for those that do not. A behavior tree is a way to build complex behavior out of small pieces, where every piece reports whether it succeeded or failed. That may seem simple, but that one idea – each piece provides success or failure – is what makes everything work.
The pieces (“nodes”) of a behavior tree come in three kinds:
- Leaves do the actual work: walk, throw rocks, leap, explode. A leaf can also be a simple check, like “is the player nearby?”, which succeeds or fails right away.
- Composites have several children and decide which ones run. The two important ones are the Sequence and the Selector.
- Decorators wrap a single child and change what it does or what it reports, like “repeat this three times” or “flip success and failure.”
A Sequence runs its children in order. If one fails, the whole Sequence stops and fails. If they all succeed, the Sequence succeeds. Think of it as “do this, and then this, and then this.”
A Selector (sometimes called a Fallback) also runs its children in order, but it stops at the first one that succeeds. It only fails if every child fails. Think of it as “try this, or else this, or else this.”
Those two together give us the ability to create a kind of simple programming language. Because a check can fail, putting a check at the start of a Sequence turns it into an if statement. Putting a few of those Sequences inside a Selector gives you if / else if / else. And since composites are also nodes, you can nest them as deep as you like.
Building it on top of the old Behavior type
Once I figured this out, the nice surprise was that my Behavior interface barely had to change. Here it is today:
export type BehaviorCompleteCallback = (success?: boolean) => void;export interface Behavior { name: string; init( sprite: Phaser.GameObjects.Sprite, goToNextState: BehaviorCompleteCallback, enemyManager: EnemyManager ): void; update?: ( sprite: Phaser.GameObjects.Sprite, goToNextState: BehaviorCompleteCallback, enemyManager: EnemyManager ) => void; cleanUp?: ( sprite: Phaser.GameObjects.Sprite, enemyManager: EnemyManager ) => void;}
The important change is the success argument on the callback. Before, a behavior could only say “I’m done.” Now it can say “I’m done, and it didn’t work.” It defaults to true, so none of the existing behaviors had to change.
The other major difference is that behaviors no longer take the name of the next state. In the old system, new ThrowRocks(state, "leftrightmarch", {...}) hard-coded where to go next. Now a behavior only reports that it finished, and whatever owns it decides what happens next. That’s what lets one behavior be a child of another.
Leaves that are true/false checks
A check is just a behavior that finishes immediately, inside init(). Here’s IsNearPlayer:
export class IsNearPlayer implements Behavior { name: string; #distance: number; constructor(name: string, distance: number) { this.name = name; this.#distance = distance; } init( sprite: Phaser.GameObjects.Sprite, goToNextState: BehaviorCompleteCallback ): void { const player = getPlayerOrThrow(); if (!isDynamicSprite(sprite)) { throw new Error("Could not update monster"); } const distance = Phaser.Math.Distance.BetweenPoints( sprite.body.center, player.body.center ); goToNextState(distance <= this.#distance); }}
The Sequence
The composites nodes are behaviors too, which means they plug into the enemy exactly like a leaf node would. A Sequence takes a list of children and runs them one at a time. When a child finishes, the Sequence cleans it up and starts the next one.
The children of a Sequence node are passed as functions that create behaviors (which I call “creators”) rather than as behaviors themselves. Each behavior keeps private state (timers, directions, rock counts), so reusing an instance on the second loop would keep state that I want to be reset.
Here’s the core of that:
#progressBehaviors(): void { let creator = this.#currentCreatorIndex < this.#creators.length ? this.#creators[this.#currentCreatorIndex] : undefined; if (!creator && this.#loopIf?.()) { this.#currentCreatorIndex = 0; creator = this.#creators[this.#currentCreatorIndex]; } if (!creator) { this.#goToNextState(true); return; } this.#behavior = creator(); this.#currentCreatorIndex += 1; this.#startBehavior();}#behaviorFinished(success: boolean = true): void { this.#behavior?.cleanUp?.(this.#sprite, this.#enemyManager); this.#behavior = undefined; if (success === false && this.#loopIf?.()) { this.#currentCreatorIndex = 0; this.#progressBehaviors(); return; } if (success === false) { this.#goToNextState(false); return; } this.#progressBehaviors();}
The loopIf option is something I added for convenience. Most of my enemies do the same thing forever, so a Sequence can restart from the top when it reaches the end, or when a child fails. (That replaces a separate Repeat decorator although I made one of those too.)
The Selector
The Selector is almost the same code with the success check reversed. A child that succeeds ends the Selector with success. A child that fails moves on to the next one. If all children fail, it fails.
#behaviorFinished(success: boolean = true): void { this.#behavior?.cleanUp?.(this.#sprite, this.#enemyManager); this.#behavior = undefined; if (success) { this.#goToNextState(true); return; } this.#progressBehaviors();}
Decorators
These are simple nodes that usually have one child and changes its behavior.
Inverterruns its child but returns the opposite of whatever its child returns.Repeatruns its child a fixed number of times, creating a fresh one each time.
I also have a special decorator-like node that is just a convenience for a common scenario:
Conditiontakes a plain function and two creators,onSuccessandonFailure, and runs whichever matches. I could build this from a Selector, a Sequence, and a check node, but it reads much better when the condition is just some enemy property like hit points.
Example: SlowPunch
SlowPunch is a slow, heavy enemy with an explosive attack. It waits until you get close, follows you, and if it catches up it charges and explodes. But if you outrun it, it should go back to following instead of exploding at nothing.
Here’s its whole brain:
constructNewBehaviorFor(state: string) { return new Sequence(state, { loopIf: () => true, creators: [ () => new WaitForActive(state, { distance: this.awareDistance, }), () => new FollowPlayer(state, { speed: this.speed, awareDistance: this.awareDistance, stopWhenCloseDistance: this.closeDistance, }), () => new Selector(state, { creators: [ () => new Inverter( state, () => new IsNearPlayer(state, this.closeDistance) ), () => new Sequence(state, { creators: [ () => new PowerUp(state, { chargeTime: 700 }), () => new LavaExplode(state, { damage: 2, hitboxRadius: 34, particleLifeSpan: 450, }), ], }), ], }), ], });}
It’s a lot easier to visualize as a tree:

When FollowPlayer stops, the Selector first asks IsNearPlayer, flipped by the Inverter. If the player is too far, the inverted check succeeds, the Selector succeeds without attacking, and the outer Sequence loops and goes back to waiting. But if the player is close, the inverted check fails, so the Selector tries its next child: the attack.
In the old system this would have been four or five named states, with the “is the player close?” logic living inside FollowPlayer or in the enemy class. Now it’s just one tree, and FollowPlayer doesn’t need to know anything about exploding.
(You might notice every node gets the same state name. That’s just a leftover from the state machine that I haven’t refactored out yet. The base monster class builds a new behavior whenever the state name changes, so as long as the whole tree shares one name, the tree just keeps running.)
Mixing trees with the state machine
I didn’t convert every enemy, and I didn’t have to. Since a tree is just a Behavior, it can be dropped into any state of the old machine. The Mountain Kingdom Boss still uses named states for its intro (wait, roar, spawn minions, march), but its attack state is now a small tree:
case "attack": this.nextState = "roar1"; this.#attackCount++; return new Condition(state, { condition: () => this.#attackCount % 2 !== 0, onSuccess: () => new Sequence(state, { creators: [ () => new PowerUp(state, { scale: 3, chargeTime: 800 }), () => new Leap(state, { /* jump in place */ }), () => new ThrowRocks(state, { rockCount: 4, /* ... */ }), ], }), onFailure: () => new Repeat(state, { count: 3, createBehavior: () => new Leap(state, { shakeOnLand: true, postAttackTime: 700 }), }), });
On odd turns the boss powers up, jumps in place, and throws rocks. On even turns it leaps at you three times. Before, that would have been two extra named states plus a counter check in the switch.
Remaining issues
The biggest win with this system is that each behavior only has to do one thing. FollowPlayer follows. IsNearPlayer checks a distance. Deciding what to do with those results is the tree’s job, so I can reuse the same pieces in very different enemies. The Air Cannon, for example, is just a looping Sequence of rotate, appear, blast, and disappear.
It’s also much easier to change a fight. Making the Mountain Kingdom Boss alternate between two attacks was a few lines in one place, rather than new states threaded through the switch.
The biggest issue, though, is that trees can’t interrupt themselves. Published behavior tree engines re-check the tree every frame, so a higher-priority branch can cut off a running action. My version is driven by callbacks, so once a long behavior starts, nothing can interrupt it.
Right now only a handful of my 35 enemies use the tree nodes directly. Everything else still uses the original state machine, and that’s okay. Being able to adopt trees one enemy, or even one state, at a time made the switch painless.
Wrapping up
When I wrote the first post, behavior trees sounded like a big, intimidating topic. In the end they took five small classes and one new boolean on a callback. The old system already had the hard part: small, self-contained behaviors that say when they’re done. Trees just let those behaviors say how it went, and let other behaviors decide what to do about it.
Next I’d like to try converting the other monsters to a single tree and see whether the readability holds up, and maybe try to come up with a way to interrupt nodes. Lots of room to grow.
Oh, and I should probably actually finish the 2.0 version of the game so I can show all this off. 😅
Photo by Kelly Sikkema on Unsplash

Leave a Reply