Game AI: decisions, steering, and pathfinding
Build believable NPC behavior from three separable layers: decide (what to
do), steer (how to move there), and path (how to route around the map).
Keep them decoupled — a behavior tree picks a target, the pathfinder produces
waypoints, steering follows them. This skill teaches the engine-neutral
algorithms; bind them to your engine via the related skills below.
When to use
- Use when implementing enemy/NPC logic: patrols, chase/flee, guard states,
group movement, or "find a path to the player".
- Use to choose between an FSM (few clear states), a behavior tree (many
reactive behaviors with priorities), or steering (smooth local movement).
- Use when integrating pathfinding: A* on a grid/graph, or driving an engine
navmesh agent.
When not to use: for the engine's concrete navmesh/agent API and baking,
use unity-navmesh, unreal-behavior-trees, or Godot's NavigationAgent2D/3D
(see that engine skill). For movement/collision feel, use physics-tuning. For
spawning waves along lanes, see the tower-defense genre skill.
Core workflow
- Pick the decision model by complexity. 2–5 states with obvious
transitions → FSM. Many behaviors, priorities, interruption, reuse → behavior
tree. Continuous "how strongly do I want each option" → utility scoring.
- Separate decision from motion. The decision layer outputs an intent
(target position, action). Steering or pathfinding turns intent into motion.
- Path on the right graph. Grid tiles, waypoint graph, or a baked navmesh.
Fewer nodes = faster A*. Prefer the engine's navmesh for 3D; A* on a grid for
tile games.
- Steer along the path, not straight to the goal — follow the next waypoint,
advancing when close, so agents round corners.
- Recompute paths sparingly. Pathfind on a timer or when the goal moves a
tile, not every frame. Cache the path; only the waypoint index advances.
- Verify by observation. Watch the agent: does it reach the goal, get stuck
on corners, oscillate between states? Draw the path and current state on
screen while tuning.
Patterns
1. Finite state machine (one state object, explicit transitions)
# Each state is a small object with enter/update/exit. The machine owns "current".
class_name State
func enter(agent): pass
func update(agent, dt) -> State: return null # return a new state to transition
func exit(agent): pass
# --- Chase state: returns Patrol when the player escapes sight range ---
class Chase extends State:
func update(agent, dt) -> State:
if not agent.can_see(agent.target):
return Patrol.new() # transition by returning next state
agent.move_toward(agent.target.position, dt)
return null # null = stay in this state
# --- Driver: call once per frame ---
func tick(dt):
var next = current.update(self, dt)
if next != null:
current.exit(self); next.enter(self); current = next
Keep transition logic inside states (or in a table), never as a growing pile
of if flags. One state owns one behavior; that is what keeps an FSM readable.
2. Behavior tree tick (composite nodes return a status)
# A node's tick() returns SUCCESS, FAILURE, or RUNNING (still working this frame).
enum Status { SUCCESS, FAILURE, RUNNING }
# Sequence: run children in order; stop at the first non-SUCCESS (logical AND).
func sequence_tick(children, agent, dt) -> int:
for child in children:
var s = child.tick(agent, dt)
if s != Status.SUCCESS:
return s # FAILURE or RUNNING short-circuits the sequence
return Status.SUCCESS
# Selector: try children until one succeeds or is RUNNING (logical OR / fallback).
func selector_tick(children, agent, dt) -> int:
for child in children:
var s = child.tick(agent, dt)
if s != Status.FAILURE:
return s # SUCCESS or RUNNING stops the search
return Status.FAILURE
A guard AI reads top-down: Selector[ Sequence[CanSeePlayer?, Chase], Patrol ]
— chase if visible, otherwise patrol. See references/behavior-trees.md for
leaf nodes, decorators (Inverter, Cooldown), and a blackboard.
3. Steering: seek and arrive (smooth, frame-rate independent)
# Seek: accelerate toward a target at full speed. Steering = desired - current.
func seek(pos, vel, target, max_speed, max_force) -> Vector2:
var desired = (target - pos).normalized() * max_speed
return (desired - vel).limit_length(max_force) # a force, not a teleport
# Arrive: like seek, but ramp speed down inside slow_radius so it stops cleanly.
func arrive(pos, vel, target, max_speed, max_force, slow_radius) -> Vector2:
var offset = target - pos
var dist = offset.length()
if dist < 0.001: return -vel # already there: kill drift
var ramped = max_speed * min(dist / slow_radius, 1.0)
var desired = offset / dist * ramped
return (desired - vel).limit_length(max_force)
# Per frame: vel += steering * dt; pos += vel * dt (always scale by dt)
4. A* heuristic must not overestimate (or paths stop being shortest)
# Match the heuristic to the movement. An ADMISSIBLE heuristic (never larger
# than the true remaining cost) keeps A* optimal.
def heuristic(a, b):
dx, dy = abs(a.x - b.x), abs(a.y - b.y)
# return dx + dy # Manhattan: 4-direction grids (no diagonals)
return (dx + dy) + (1.414 - 2) * min(dx, dy) # octile: 8-direction grids
# f(n) = g(n) + h(n): g = cost from start, h = heuristic to goal.
# Overestimating h is faster but no longer guarantees the shortest path.
The full A* loop (priority queue, came_from reconstruction, grid + waypoint
graphs) is in references/pathfinding.md.
Pitfalls
- Pathfinding every frame tanks the frame rate. Recompute on a timer or only
when the target moves to a new tile; follow the cached waypoints in between.
- Steering straight to the goal instead of to the next waypoint makes agents
hug walls and corners. Follow the path; advance the waypoint when within radius.
- Inadmissible A* heuristic (e.g. Euclidean distance scaled up, or Manhattan
on a diagonal grid) returns fast but non-shortest paths. Pick the heuristic
that matches your allowed moves.
- Behavior tree leaves that never return RUNNING for multi-frame actions
(walking, playing an animation) cause the tree to restart the action every
tick. Return RUNNING until the action completes.
- FSM transition spaghetti: scattering
if state == ... checks everywhere
recreates the mess an FSM exists to prevent. Keep transitions in the state.
- No line-of-sight or stuck check → agents grind into walls forever. Add a
timeout that forces a repath or a state change.
References
references/pathfinding.md — complete A* (priority queue, reconstruction),
grid vs waypoint graphs, when to defer to an engine navmesh.
references/behavior-trees.md — node taxonomy, leaf/decorator implementations,
blackboard, and FSM-vs-BT selection.
Related skills
unity-navmesh, unreal-behavior-trees — concrete engine AI/navigation APIs.
physics-tuning — movement, collision response, and agent radius.
procedural-gen — generating the graph/level the AI navigates.
tower-defense, fps-shooter — genres that compose this skill.
1---
2name: game-ai
3description: >
4 Design NPC and enemy decision-making with finite state machines, behavior
5 trees, steering behaviors, and A* pathfinding — engine-neutral algorithms
6 that pair with the detected engine's navigation API. Use when building enemy
7 AI, an FSM or behavior tree, steering/flocking, or pathfinding, or when the
8 user mentions state machine, behavior tree, blackboard, A*, navmesh, seek, or
9 patrol/chase.
10---
11
12# Game AI: decisions, steering, and pathfinding
13
14Build believable NPC behavior from three separable layers: **decide** (what to
15do), **steer** (how to move there), and **path** (how to route around the map).
16Keep them decoupled — a behavior tree picks a target, the pathfinder produces
17waypoints, steering follows them. This skill teaches the engine-neutral
18algorithms; bind them to your engine via the related skills below.
19
20## When to use
21
22- Use when implementing enemy/NPC logic: patrols, chase/flee, guard states,
23 group movement, or "find a path to the player".
24- Use to choose between an **FSM** (few clear states), a **behavior tree** (many
25 reactive behaviors with priorities), or **steering** (smooth local movement).
26- Use when integrating pathfinding: A* on a grid/graph, or driving an engine
27 navmesh agent.
28
29**When *not* to use:** for the engine's concrete navmesh/agent API and baking,
30use `unity-navmesh`, `unreal-behavior-trees`, or Godot's `NavigationAgent2D/3D`
31(see that engine skill). For movement/collision feel, use `physics-tuning`. For
32spawning waves along lanes, see the `tower-defense` genre skill.
33
34## Core workflow
35
361. **Pick the decision model by complexity.** 2–5 states with obvious
37 transitions → FSM. Many behaviors, priorities, interruption, reuse → behavior
38 tree. Continuous "how strongly do I want each option" → utility scoring.
392. **Separate decision from motion.** The decision layer outputs an *intent*
40 (target position, action). Steering or pathfinding turns intent into motion.
413. **Path on the right graph.** Grid tiles, waypoint graph, or a baked navmesh.
42 Fewer nodes = faster A*. Prefer the engine's navmesh for 3D; A* on a grid for
43 tile games.
444. **Steer along the path**, not straight to the goal — follow the next waypoint,
45 advancing when close, so agents round corners.
465. **Recompute paths sparingly.** Pathfind on a timer or when the goal moves a
47 tile, not every frame. Cache the path; only the waypoint index advances.
486. **Verify by observation.** Watch the agent: does it reach the goal, get stuck
49 on corners, oscillate between states? Draw the path and current state on
50 screen while tuning.
51
52## Patterns
53
54### 1. Finite state machine (one state object, explicit transitions)
55
56```gdscript
57# Each state is a small object with enter/update/exit. The machine owns "current".
58class_name State
59func enter(agent): pass
60func update(agent, dt) -> State: return null # return a new state to transition
61func exit(agent): pass
62
63# --- Chase state: returns Patrol when the player escapes sight range ---
64class Chase extends State:
65 func update(agent, dt) -> State:
66 if not agent.can_see(agent.target):
67 return Patrol.new() # transition by returning next state
68 agent.move_toward(agent.target.position, dt)
69 return null # null = stay in this state
70
71# --- Driver: call once per frame ---
72func tick(dt):
73 var next = current.update(self, dt)
74 if next != null:
75 current.exit(self); next.enter(self); current = next
76```
77
78Keep transition logic *inside* states (or in a table), never as a growing pile
79of `if` flags. One state owns one behavior; that is what keeps an FSM readable.
80
81### 2. Behavior tree tick (composite nodes return a status)
82
83```gdscript
84# A node's tick() returns SUCCESS, FAILURE, or RUNNING (still working this frame).
85enum Status { SUCCESS, FAILURE, RUNNING }
86
87# Sequence: run children in order; stop at the first non-SUCCESS (logical AND).
88func sequence_tick(children, agent, dt) -> int:
89 for child in children:
90 var s = child.tick(agent, dt)
91 if s != Status.SUCCESS:
92 return s # FAILURE or RUNNING short-circuits the sequence
93 return Status.SUCCESS
94
95# Selector: try children until one succeeds or is RUNNING (logical OR / fallback).
96func selector_tick(children, agent, dt) -> int:
97 for child in children:
98 var s = child.tick(agent, dt)
99 if s != Status.FAILURE:
100 return s # SUCCESS or RUNNING stops the search
101 return Status.FAILURE
102```
103
104A guard AI reads top-down: `Selector[ Sequence[CanSeePlayer?, Chase], Patrol ]`
105— chase if visible, otherwise patrol. See `references/behavior-trees.md` for
106leaf nodes, decorators (Inverter, Cooldown), and a blackboard.
107
108### 3. Steering: seek and arrive (smooth, frame-rate independent)
109
110```gdscript
111# Seek: accelerate toward a target at full speed. Steering = desired - current.
112func seek(pos, vel, target, max_speed, max_force) -> Vector2:
113 var desired = (target - pos).normalized() * max_speed
114 return (desired - vel).limit_length(max_force) # a force, not a teleport
115
116# Arrive: like seek, but ramp speed down inside slow_radius so it stops cleanly.
117func arrive(pos, vel, target, max_speed, max_force, slow_radius) -> Vector2:
118 var offset = target - pos
119 var dist = offset.length()
120 if dist < 0.001: return -vel # already there: kill drift
121 var ramped = max_speed * min(dist / slow_radius, 1.0)
122 var desired = offset / dist * ramped
123 return (desired - vel).limit_length(max_force)
124
125# Per frame: vel += steering * dt; pos += vel * dt (always scale by dt)
126```
127
128### 4. A* heuristic must not overestimate (or paths stop being shortest)
129
130```python
131# Match the heuristic to the movement. An ADMISSIBLE heuristic (never larger
132# than the true remaining cost) keeps A* optimal.
133def heuristic(a, b):
134 dx, dy = abs(a.x - b.x), abs(a.y - b.y)
135 # return dx + dy # Manhattan: 4-direction grids (no diagonals)
136 return (dx + dy) + (1.414 - 2) * min(dx, dy) # octile: 8-direction grids
137# f(n) = g(n) + h(n): g = cost from start, h = heuristic to goal.
138# Overestimating h is faster but no longer guarantees the shortest path.
139```
140
141The full A* loop (priority queue, `came_from` reconstruction, grid + waypoint
142graphs) is in `references/pathfinding.md`.
143
144## Pitfalls
145
146- **Pathfinding every frame** tanks the frame rate. Recompute on a timer or only
147 when the target moves to a new tile; follow the cached waypoints in between.
148- **Steering straight to the goal** instead of to the next waypoint makes agents
149 hug walls and corners. Follow the path; advance the waypoint when within radius.
150- **Inadmissible A\* heuristic** (e.g. Euclidean distance scaled up, or Manhattan
151 on a diagonal grid) returns fast but *non-shortest* paths. Pick the heuristic
152 that matches your allowed moves.
153- **Behavior tree leaves that never return RUNNING** for multi-frame actions
154 (walking, playing an animation) cause the tree to restart the action every
155 tick. Return RUNNING until the action completes.
156- **FSM transition spaghetti**: scattering `if state == ...` checks everywhere
157 recreates the mess an FSM exists to prevent. Keep transitions in the state.
158- **No line-of-sight or stuck check** → agents grind into walls forever. Add a
159 timeout that forces a repath or a state change.
160
161## References
162
163- `references/pathfinding.md` — complete A* (priority queue, reconstruction),
164 grid vs waypoint graphs, when to defer to an engine navmesh.
165- `references/behavior-trees.md` — node taxonomy, leaf/decorator implementations,
166 blackboard, and FSM-vs-BT selection.
167
168## Related skills
169
170- `unity-navmesh`, `unreal-behavior-trees` — concrete engine AI/navigation APIs.
171- `physics-tuning` — movement, collision response, and agent radius.
172- `procedural-gen` — generating the graph/level the AI navigates.
173- `tower-defense`, `fps-shooter` — genres that compose this skill.