Designs classical game AI as three layers: decision (FSM, behavior trees, utility, GOAP/HTN), NavMesh/A-star pathfinding with funnel smoothing, and Reynolds steering/flocking plus bounded perception. Use when building or debugging enemy/NPC agents that get stuck, jitter, or clump. Not for netcode replication, animation blending, ML/RL policy training, or dialogue trees with no movement loop.
Decision-making (what to do), pathfinding (how to get there), and steering (how to move) are three separate layers. Keep them separate and most AI bugs disappear.
Three layers, one direction: Decision → Pathfinding → Steering. Decision sets a goal; pathing finds the route; steering moves the body. Violating this one-way data flow is the single most common source of AI bugs.
When to Use
Activate when the task involves:
Choosing a decision architecture (FSM vs behavior tree vs utility AI vs GOAP/HTN) for an agent.
Implementing a behavior tree with composites, decorators, services, and a blackboard.
Pathfinding on a NavMesh or grid: A*, path smoothing (funnel), hierarchical/portal graphs, flow fields.
Replicating AI state across the network — own the behavior; let multiplayer-netcode own replication and authority.
Playing/blending the animations an AI decision triggers — that is runtime-animation (locomotion blend trees, IK). This skill outputs intent (move here, attack); the animation skill realizes it.
ML/RL training pipelines — this skill is classical, hand-authored game AI, not neural policy training.
Dialogue trees / narrative scripting with no autonomous movement or decision loop.
Prerequisites
A game engine or framework with a navigation system (NavMesh, grid, or graph) and basic vector math utilities.
Services: run on a cadence while a subtree is active (e.g. refresh "best target" every 0.5 s).
Leaves: condition checks and actions (MoveTo, Attack, PlayAnim-request).
Blackboard: shared key/value memory (target, lastKnownPos, homePos) — the only coupling between nodes.
enum Status { Success, Failure, Running }
abstract class Node { public abstract Status Tick(Blackboard bb); }
class Sequence : Node {
readonly Node[] kids; int i;
public override Status Tick(Blackboard bb) {
for (; i < kids.Length; i++) {
var s = kids[i].Tick(bb);
if (s != Status.Success) return s; // Running or Failure short-circuits
}
i = 0; return Status.Success;
}
}
class Selector : Node {
readonly Node[] kids;
public override Status Tick(Blackboard bb) {
foreach (var k in kids) {
var s = k.Tick(bb);
if (s != Status.Failure) return s; // first non-failure wins
}
return Status.Failure;
}
}
3. Implement GOAP (when action sequencing is needed)
Each action declares preconditions and effects (as world-state booleans) plus a cost. The planner runs A* over world states (not space): start = current world state, goal = desired state, neighbors = applicable actions. The resulting plan is an ordered action list the agent executes until the world changes and it replans.
A* on the NavMesh polygon graph (or grid). Heuristic = octile/Euclidean; keep it admissible.
String-pull / funnel the polygon corridor into a minimal set of waypoints — raw A* output hugs cell corners and looks robotic.
Hierarchical (portal/region graph) for large maps: plan coarse region-to-region, refine locally.
Flow fields when many agents share one goal (tower defense, RTS swarms): compute a Dijkstra field once, every agent samples the gradient.
List<Node> AStar(Node start, Node goal) {
var open = new PriorityQueue<Node, float>();
var g = new Dictionary<Node, float> { [start] = 0 };
var came = new Dictionary<Node, Node>();
open.Enqueue(start, Heuristic(start, goal));
while (open.Count > 0) {
var cur = open.Dequeue();
if (cur == goal) return Reconstruct(came, cur);
foreach (var (nbr, cost) in cur.Neighbors) {
float ng = g[cur] + cost;
if (ng < g.GetValueOrDefault(nbr, float.MaxValue)) {
g[nbr] = ng; came[nbr] = cur;
open.Enqueue(nbr, ng + Heuristic(nbr, goal)); // f = g + h
}
}
}
return null; // no path
}
5. Implement steering (Reynolds) — movement, not pathing
Steering produces a desired velocity; combine behaviors by weighted sum or priority, then clamp to max force/speed.
Drive path following by seeking the next funnel waypoint with Arrive on the last one. Avoidance (RVO/ORCA or feelers) sits on top to prevent agent–agent overlap.
6. Implement perception
Sight: target within view distance AND within FOV half-angle AND an unobstructed LoS raycast.
Hearing: stimuli (gunshots, footsteps) register as events with intensity falloff.
Memory: store lastKnownPosition + timestamp; investigate, then forget after a timeout so agents don't become omniscient.
Before tuning, add debug draws for: path lines, FOV cones, current BT node, target position, steering force vector, and perception range spheres. AI is nearly impossible to debug blind.
Examples
Engine mappings
Unreal: Behavior Trees + Blackboard (built-in), AIController, NavMesh (Recast),
EQS for environment queries (cover, flank points), Perception component.
Unity: NavMeshAgent + NavMesh baking; behavior via Behavior Designer / custom BT;
A* Pathfinding Project for grids/flow; steering hand-rolled or via add-ons.
Godot 4: NavigationAgent2D/3D + NavigationServer (funnel built in), Area-based
detection for perception, custom BT/FSM scripts.
Debugging scenarios
Input : "Agents jitter / vibrate when they reach the target."
Cause : Seek with no Arrive — they overshoot and snap back each frame.
Output: switch to Arrive (slow inside a radius), add a stop threshold, and stop
repathing once within acceptance radius.
Input : "Enemies clump into one spot and overlap."
Cause : no agent avoidance / separation.
Output: add Separation steering or RVO/ORCA; give each a slot/formation offset
around the target instead of all seeking the exact same point.
Input : "Agent oscillates between Patrol and Investigate every frame."
Cause : perception flickers on/off at the edge of detection range.
Output: add hysteresis (separate detect/lose thresholds) and a cooldown decorator
on the transition.
Pitfalls
Never couple BT nodes by direct references. The blackboard is the only shared state. Nodes that reference each other directly create spaghetti that is impossible to reorder or reuse.
Never use raw Seek at the destination. Seek has no slow-down — agents overshoot and jitter. Always use Arrive near goals with a stop threshold.
Never skip funnel smoothing. Unsmoothed A* paths hug polygon corners and look broken even when "correct."
Never repath every frame. Repath on a cadence or on significant target movement; stagger across agents (time-slicing) to avoid frame spikes.
Never give perception omniscience. FOV, range, LoS, and memory timeout make AI feel fair and fool-able. Without a memory timeout, agents never "forget" and feel psychic.
Never let all agents seek the exact same point. Without separation or formation slots, they clump and overlap. Use RVO/ORCA or slot offsets.
Never use an inadmissible A heuristic.* An overestimating heuristic produces suboptimal or broken paths. Use octile for grids, Euclidean for open NavMesh.
Never blend decision and steering layers. Decision sets a goal; pathing finds the route; steering moves the body. If steering feeds back into decision logic, you get circular dependencies and infinite oscillation.
GOAP/HTN: never execute a stale plan. Replan when the world state invalidates the current plan — otherwise agents act on outdated assumptions.
Verification
Decision, pathfinding, and steering are separate layers with one-way data flow (decision → path → steer).
The chosen decision architecture fits the agent complexity (FSM for trivial, BT/utility/GOAP for richer).
Behavior tree nodes return Success/Failure/Running and communicate only through the blackboard.
A* uses an admissible heuristic and its corridor is funnel-smoothed before following.
Large maps use hierarchical pathfinding; shared-goal swarms use flow fields.
Steering uses Arrive (not raw Seek) near goals and clamps to max force/speed.
Agent–agent avoidance (separation/RVO) prevents clumping and overlap.
Perception is bounded by range, FOV, line-of-sight, and a memory timeout.
Expensive work (repathing, perception scans) is throttled and staggered across agents.
Debug visualization exists for paths, FOV cones, current state/node, and targets.
(GOAP/HTN) Planner replans when the world state invalidates the current plan.
Related skills
runtime-animation — Realizes AI intent as locomotion blend trees, foot IK, and attack animations.
multiplayer-netcode — Replicates AI agent state/decisions and resolves authority in networked play.
performance-profiling — Time-slice perception/pathing and profile A* and steering across many agents.
custom-physics-solvers — Spatial math behind steering, avoidance, and raycast perception.
External resources
Craig Reynolds, "Steering Behaviors For Autonomous Characters".
"Game AI Pro" series (behavior trees, GOAP, utility, influence maps).
1---
2name: game-ai-behavior
3version: 1.0.1
4description: "Designs classical game AI as three layers: decision (FSM, behavior trees, utility, GOAP/HTN), NavMesh/A-star pathfinding with funnel smoothing, and Reynolds steering/flocking plus bounded perception. Use when building or debugging enemy/NPC agents that get stuck, jitter, or clump. Not for netcode replication, animation blending, ML/RL policy training, or dialogue trees with no movement loop."
5risk: safe
6source: opus
7date_added: 2026-06-27
8metadata:
9 source: https://skillmd.com/skills/kayforkind/game-ai-behavior
10---
1112# Game AI & Behavior
1314Decision-making (what to do), pathfinding (how to get there), and steering (how to move) are three separate layers. Keep them separate and most AI bugs disappear.
1516**Three layers, one direction:** Decision → Pathfinding → Steering. Decision sets a goal; pathing finds the route; steering moves the body. Violating this one-way data flow is the single most common source of AI bugs.
1718## When to Use
1920Activate when the task involves:
2122- Choosing a **decision architecture** (FSM vs behavior tree vs utility AI vs GOAP/HTN) for an agent.
23- Implementing a **behavior tree** with composites, decorators, services, and a **blackboard**.
24- **Pathfinding** on a NavMesh or grid: A*, path smoothing (funnel), hierarchical/portal graphs, flow fields.
25- **Steering**: seek, flee, arrive, pursue, wander, obstacle/agent avoidance, path following, flocking.
26- **Perception**: sight cones, line-of-sight raycasts, hearing/stimulus, target memory and forgetting.
27- **Spatial reasoning**: influence maps, cover/EQS-style environment queries, tactical positioning.
28- Debugging agents that get **stuck, jitter, oscillate between states, or clump**.
2930**Trigger keywords:** enemy AI, NPC behavior, behavior tree, blackboard, decorator, state machine, utility AI, GOAP, HTN planner, NavMesh, A*, path smoothing, funnel, flow field, steering, flocking/boids, perception, sight cone, influence map, EQS.
3132### Do not use for
3334- **Replicating AI state across the network** — own the *behavior*; let `multiplayer-netcode` own replication and authority.
35- **Playing/blending the animations** an AI decision triggers — that is `runtime-animation` (locomotion blend trees, IK). This skill outputs intent (move here, attack); the animation skill realizes it.
36- **ML/RL training pipelines** — this skill is classical, hand-authored game AI, not neural policy training.
37- **Dialogue trees / narrative scripting** with no autonomous movement or decision loop.
3839## Prerequisites
4041- A game engine or framework with a navigation system (NavMesh, grid, or graph) and basic vector math utilities.
42- For Unreal: built-in Behavior Trees, Blackboard, AIController, NavMesh (Recast), EQS, Perception component.
43- For Unity: NavMeshAgent + NavMesh baking; behavior via Behavior Designer or custom BT; A* Pathfinding Project for grids/flow.
44- For Godot 4: NavigationAgent2D/3D + NavigationServer (funnel built in), Area-based detection for perception, custom BT/FSM scripts.
45- Windows host is primary (PowerShell). No external CLI tools required — this skill is architecture and code patterns, not a build pipeline.
4647## Procedure
4849### 1. Pick the decision architecture
5051| Architecture | Strength | Use when |
52|---|---|---|
53| **FSM / Hierarchical FSM** | Simple, debuggable | Few states, clear transitions (turret, simple guard) |
54| **Behavior Tree** | Modular, reusable, designer-friendly | Most action-game enemies/NPCs |
55| **Utility AI** | Smooth, emergent priority from scored options | Sims, many competing needs (The Sims-like) |
56| **GOAP** | Plans action sequences to reach a goal | Emergent, tool-using agents (F.E.A.R.-style) |
57| **HTN** | Authored task decomposition with planning | Squad tactics, structured plans |
5859**Default:** Behavior Tree + Blackboard, layered over NavMesh pathfinding and steering.
6061### 2. Implement the behavior tree core
6263Nodes return **Success / Failure / Running**. Ticking is top-down each frame; `Running` lets actions span frames.
6465- **Composites**: `Sequence` (AND — fail-fast), `Selector` (OR — succeed-fast), `Parallel`.
66- **Decorators**: invert, cooldown, condition guard, repeat, time-limit.
67- **Services**: run on a cadence while a subtree is active (e.g. refresh "best target" every 0.5 s).
68- **Leaves**: condition checks and actions (MoveTo, Attack, PlayAnim-request).
69- **Blackboard**: shared key/value memory (target, lastKnownPos, homePos) — the *only* coupling between nodes.
7071```csharp
72enum Status { Success, Failure, Running }
73abstract class Node { public abstract Status Tick(Blackboard bb); }
7475class Sequence : Node {
76 readonly Node[] kids; int i;
77 public override Status Tick(Blackboard bb) {
78 for (; i < kids.Length; i++) {
79 var s = kids[i].Tick(bb);
80 if (s != Status.Success) return s; // Running or Failure short-circuits
81 }
82 i = 0; return Status.Success;
83 }
84}
8586class Selector : Node {
87 readonly Node[] kids;
88 public override Status Tick(Blackboard bb) {
89 foreach (var k in kids) {
90 var s = k.Tick(bb);
91 if (s != Status.Failure) return s; // first non-failure wins
92 }
93 return Status.Failure;
94 }
95}
96```
9798Typical combat tree: `Selector[ Sequence(CanSeeTarget?, Attack), Sequence(HasLastKnownPos?, Investigate), Patrol ]`.
99100### 3. Implement GOAP (when action sequencing is needed)
101102Each **action** declares preconditions and effects (as world-state booleans) plus a cost. The planner runs **A\* over world states** (not space): start = current world state, goal = desired state, neighbors = applicable actions. The resulting plan is an ordered action list the agent executes until the world changes and it replans.
103104```text
105Actions: Reload {pre: hasAmmoBox; eff: weaponLoaded; cost:2}
106 AttackTarget {pre: weaponLoaded, targetVisible; eff: targetDead; cost:1}
107Goal: targetDead
108Plan: A* finds [Reload, AttackTarget] when weapon is empty.
109```
110111### 4. Implement pathfinding: A* then smooth
1121131. **A\*** on the NavMesh polygon graph (or grid). Heuristic = octile/Euclidean; keep it admissible.
1142. **String-pull / funnel** the polygon corridor into a minimal set of waypoints — raw A* output hugs cell corners and looks robotic.
1153. **Hierarchical** (portal/region graph) for large maps: plan coarse region-to-region, refine locally.
1164. **Flow fields** when *many* agents share one goal (tower defense, RTS swarms): compute a Dijkstra field once, every agent samples the gradient.
117118```csharp
119List<Node> AStar(Node start, Node goal) {
120 var open = new PriorityQueue<Node, float>();
121 var g = new Dictionary<Node, float> { [start] = 0 };
122 var came = new Dictionary<Node, Node>();
123 open.Enqueue(start, Heuristic(start, goal));
124 while (open.Count > 0) {
125 var cur = open.Dequeue();
126 if (cur == goal) return Reconstruct(came, cur);
127 foreach (var (nbr, cost) in cur.Neighbors) {
128 float ng = g[cur] + cost;
129 if (ng < g.GetValueOrDefault(nbr, float.MaxValue)) {
130 g[nbr] = ng; came[nbr] = cur;
131 open.Enqueue(nbr, ng + Heuristic(nbr, goal)); // f = g + h
132 }
133 }
134 }
135 return null; // no path
136}
137```
138139### 5. Implement steering (Reynolds) — movement, not pathing
140141Steering produces a desired velocity; combine behaviors by **weighted sum or priority**, then clamp to max force/speed.
142143```csharp
144Vector3 Seek(Vector3 pos, Vector3 target, Vector3 vel, float maxSpeed, float maxForce) {
145 Vector3 desired = (target - pos).normalized * maxSpeed;
146 return Vector3.ClampMagnitude(desired - vel, maxForce); // steering force
147}
148// Arrive: scale desired speed down inside a slowing radius to avoid overshoot.
149// Flocking = Separation (push apart) + Alignment (match heading) + Cohesion (toward center).
150// Obstacle avoidance: feeler rays; steer away from the nearest predicted collision.
151```
152153Drive **path following** by seeking the next funnel waypoint with `Arrive` on the last one. Avoidance (RVO/ORCA or feelers) sits on top to prevent agent–agent overlap.
154155### 6. Implement perception
156157- **Sight**: target within view distance AND within FOV half-angle AND an unobstructed LoS raycast.
158- **Hearing**: stimuli (gunshots, footsteps) register as events with intensity falloff.
159- **Memory**: store `lastKnownPosition` + timestamp; investigate, then forget after a timeout so agents don't become omniscient.
160161```csharp
162bool CanSee(Transform eye, Transform target, float range, float fovDeg) {
163 Vector3 to = target.position - eye.position;
164 if (to.magnitude > range) return false;
165 if (Vector3.Angle(eye.forward, to) > fovDeg * 0.5f) return false;
166 return !Physics.Raycast(eye.position, to.normalized, to.magnitude, obstacleMask);
167}
168```
169170### 7. Add debug visualization first
171172Before tuning, add debug draws for: path lines, FOV cones, current BT node, target position, steering force vector, and perception range spheres. AI is nearly impossible to debug blind.
173174## Examples
175176### Engine mappings
177178```text
179Unreal: Behavior Trees + Blackboard (built-in), AIController, NavMesh (Recast),
180 EQS for environment queries (cover, flank points), Perception component.
181Unity: NavMeshAgent + NavMesh baking; behavior via Behavior Designer / custom BT;
182 A* Pathfinding Project for grids/flow; steering hand-rolled or via add-ons.
183Godot 4: NavigationAgent2D/3D + NavigationServer (funnel built in), Area-based
184 detection for perception, custom BT/FSM scripts.
185```
186187### Debugging scenarios
188189```
190Input : "Agents jitter / vibrate when they reach the target."
191Cause : Seek with no Arrive — they overshoot and snap back each frame.
192Output: switch to Arrive (slow inside a radius), add a stop threshold, and stop
193 repathing once within acceptance radius.
194```
195196```
197Input : "Enemies clump into one spot and overlap."
198Cause : no agent avoidance / separation.
199Output: add Separation steering or RVO/ORCA; give each a slot/formation offset
200 around the target instead of all seeking the exact same point.
201```
202203```
204Input : "Agent oscillates between Patrol and Investigate every frame."
205Cause : perception flickers on/off at the edge of detection range.
206Output: add hysteresis (separate detect/lose thresholds) and a cooldown decorator
207 on the transition.
208```
209210## Pitfalls
2112121. **Never couple BT nodes by direct references.** The blackboard is the *only* shared state. Nodes that reference each other directly create spaghetti that is impossible to reorder or reuse.
2132. **Never use raw Seek at the destination.** Seek has no slow-down — agents overshoot and jitter. Always use `Arrive` near goals with a stop threshold.
2143. **Never skip funnel smoothing.** Unsmoothed A* paths hug polygon corners and look broken even when "correct."
2154. **Never repath every frame.** Repath on a cadence or on significant target movement; stagger across agents (time-slicing) to avoid frame spikes.
2165. **Never give perception omniscience.** FOV, range, LoS, and memory timeout make AI feel fair and fool-able. Without a memory timeout, agents never "forget" and feel psychic.
2176. **Never let all agents seek the exact same point.** Without separation or formation slots, they clump and overlap. Use RVO/ORCA or slot offsets.
2187. **Never use an inadmissible A* heuristic.** An overestimating heuristic produces suboptimal or broken paths. Use octile for grids, Euclidean for open NavMesh.
2198. **Never blend decision and steering layers.** Decision sets a goal; pathing finds the route; steering moves the body. If steering feeds back into decision logic, you get circular dependencies and infinite oscillation.
2209. **GOAP/HTN: never execute a stale plan.** Replan when the world state invalidates the current plan — otherwise agents act on outdated assumptions.
221222## Verification
223224- [ ] Decision, pathfinding, and steering are separate layers with one-way data flow (decision → path → steer).
225- [ ] The chosen decision architecture fits the agent complexity (FSM for trivial, BT/utility/GOAP for richer).
226- [ ] Behavior tree nodes return Success/Failure/Running and communicate only through the blackboard.
227- [ ] A* uses an admissible heuristic and its corridor is funnel-smoothed before following.
228- [ ] Large maps use hierarchical pathfinding; shared-goal swarms use flow fields.
229- [ ] Steering uses Arrive (not raw Seek) near goals and clamps to max force/speed.
230- [ ] Agent–agent avoidance (separation/RVO) prevents clumping and overlap.
231- [ ] Perception is bounded by range, FOV, line-of-sight, and a memory timeout.
232- [ ] Expensive work (repathing, perception scans) is throttled and staggered across agents.
233- [ ] Debug visualization exists for paths, FOV cones, current state/node, and targets.
234- [ ] (GOAP/HTN) Planner replans when the world state invalidates the current plan.
235236## Related skills
237238- **runtime-animation** — Realizes AI intent as locomotion blend trees, foot IK, and attack animations.
239- **multiplayer-netcode** — Replicates AI agent state/decisions and resolves authority in networked play.
240- **performance-profiling** — Time-slice perception/pathing and profile A* and steering across many agents.
241- **custom-physics-solvers** — Spatial math behind steering, avoidance, and raycast perception.
242243### External resources
244245- Craig Reynolds, "Steering Behaviors For Autonomous Characters".
246- "Game AI Pro" series (behavior trees, GOAP, utility, influence maps).
247- Recast/Detour NavMesh documentation; funnel (string-pulling) algorithm.
Run npx get-skill add kayforkind/game-ai-behavior in your terminal (requires Node.js), paste this page's agent-chat prompt into Claude, Cursor, or any MCP-connected agent, or download the SKILL.md file and copy it into your agent's skills directory.
Designs classical game AI as three layers: decision (FSM, behavior trees, utility, GOAP/HTN), NavMesh/A-star pathfinding with funnel smoothing, and Reynolds steering/flocking plus bounded perception. Use when building or debugging enemy/NPC agents that get stuck, jitter, or clump. Not for netcode replication, animation blending, ML/RL policy training, or dialogue trees with no movement loop. It is listed under Coding & Dev Tools on SkillMD.
This skill has not completed SkillMD's automated safety review yet. Independent scanners report: SkillSpector: PASS, Skill Scanner: PASS. Capability flags: docs only. SkillMD never runs a skill's scripts for you; review the SKILL.md before installing.
This skill is tagged as working with Claude Code, Claude.ai, OpenAI Codex. SKILL.md is an open format, so most agents that read a skills directory can load it too.
Yes. Installing skills from SkillMD is free, and the skill stays under its author's original license.
Kayforkind (@kayforkind) published this skill. Their other Agent Skills are listed on their SkillMD profile.