agentleFS
nick-vasnick-vas/hyperdot/.agents/skills/game-ai/SKILL.md

game-ai

Skill1 starsChanged 3 days agoApache-2.0View on GitHub

Use when a Godot game has enemies, companions or opponents that decide, perceive or move on their own (state machines, behaviour trees, utility AI, planners, steering, navigation), or when an AI dithers, gets stuck or is hard to test.

7 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

5 rules. 0 are common, 4 are distinctive, and 1 is very specific to this project.

  • 0

    Common

    Most of the 7 edited versions we read keep these.

  • 4

    Distinctive

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Start with a state machine.

    line 25
  2. Distinctive:

    Every long action handles abort.

    line 34
  3. Distinctive:

    Keep leaves small and data in the context object, not a stringly-typed blackboard for everything.

    line 35
  4. Very specific:

    Start it deferred (CallDeferred or _ = WaitForNavigationReady(...)), not awaited inside _Ready.

    line 133
  5. Distinctive:

    Test AI at the largest coordinates the game uses, not only in a small level at the origin.

    line 157

“Common” is measured: kept by at least 6 in 10 of the 7 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Game AI in Godot 4 (C#)

Pick the simplest decision structure that holds, keep it in plain C# so it is tested without the engine, and wait for navigation before trusting a path. Tested implementations: ${CLAUDE_PLUGIN_ROOT}/examples/csharp/src/Example.Core/Ai/ (Utility.cs, BehaviorTree.cs, Goap.cs, Steering.cs, Aim.cs, Perception.cs) with ${CLAUDE_PLUGIN_ROOT}/examples/csharp/tests/Example.Core.Tests/AiTests.cs and AimTests.cs. Sources and measurements: ${CLAUDE_PLUGIN_ROOT}/docs/game-ai.md.

1. Which structure

StructureFitsBreaks whenWatch for
State machine3 to 8 states with clear transitions: patrol, chase, attack; doors; boss phasesOne behaviour is needed from several states, or every state links to every other ("state explosion")Duplicated states that only differ in where they return to
Hierarchical state machineModes with sub-modes; an interruption that must resume where it was (a history state)Priorities change with context
Behaviour treePriority-ordered, reactive behaviour that designers read: combat, squad rolesTens of float priorities among siblings (Halo 2 made relevance yes or no for this reason)A selector that never interrupts a running lower branch
Utility AIMany close options: tactics, needs (The Sims), RPG choices, economyScores nobody can explainFlip-flopping between two near-equal actions
GOAPMany character types sharing goals with different action sets; multi-step plans nobody wired (F.E.A.R.)The search costs more than the frameReplanning every frame; forward search
HTNDesigner-written multi-step behaviour with priorities by method orderPlans the designer did not foresee are neededReplanning on the plan's own effects cancels deliberate steps

Start with a state machine; move up when its failure mode appears, not before. F.E.A.R.'s soldiers ran a state machine of three states (go to, animate, use object) with a planner choosing what to put in them. When enemies come (not how strong): Left 4 Dead's director, PacingDirector (docs/valve.md 4).

2. Behaviour trees

  • Composites re-evaluate from the first child every tick, so a higher-priority branch interrupts at once, and the branch it interrupts is told (Abort): stop the animation, release the cover point, clear the path. The C# example's Selector and Sequence do this; a "passive" selector that only resumes the running child does not react.
  • Every long action handles abort. Abrupt aborts have side effects: a reload interrupted half-way needs a rule.
  • Keep leaves small and data in the context object, not a stringly-typed blackboard for everything.
  • A tree runs a decided behaviour; a state machine above it switches modes. Retries, cooldowns, utility logs, disabled data: pitfalls.md.

3. Utility AI

  • Each consideration maps one fact, scaled to 0..1, through a response curve (Curves.Linear, Power, Logistic, Inverted); an action's score is the product, so any consideration at 0 vetoes it. Products shrink with more factors: UtilityAction.Score compensates (Dave Mark's makeup factor) so an action that checks four things is not punished.
  • Weights rank groups: 1 for normal actions, 2 or more for emergencies (flee, heal).
  • Momentum against dithering: two actions at 0.5 with ±10% noise switched 502 times in 1000 ticks with no bonus and 0 times with 25% (UtilitySelector(..., momentum: 0.25f)). Keep the bonus above the noise; pair it with a cooldown consideration, or commit until the action ends, so real changes still win.
  • Log LastScores per decision: "why did it do that" is answered from the numbers.

4. GOAP

  • Actions declare preconditions, effects and a cost; GoapPlanner.Plan(state, goal, actions) searches backwards from the goal, so actions irrelevant to it cost nothing. A forward search took 110 ms and gave up on a six-step plan hidden among 20 cheap irrelevant actions; backward, it plans in microseconds.
  • Cap the search (maxExpanded) and treat null as "no plan": fall back to a default behaviour. Plan(..., out int expanded) reports the work done; assert on it, not on wall time, which fails under load.
  • Replan on events (the goal changed, the plan failed or was invalidated), not every frame and not on the plan's own effects. F.E.A.R. kept one goal active at a time and spread expensive checks across frames as cached facts.
  • Checks that cost (line of sight, a path) belong in the action's run-time check, not the world state.
  • Price actions from the situation instead of writing range rules: GoapPlanner.Plan(state, goal, actions, costOf: a => ...) with walking costing the distance. Chris Conway's Tomb Raider example: 20 m away, melee 1 + walk 20 = 21 loses to ranged 10 + walk 1, and out of ammo the same actions run in to melee with no rule to change (GoapCostsFollowTheSituation).
  • Plans are short. Eric Jacopin's logs of F.E.A.R., Shadow of Mordor and a Rise of the Tomb Raider alpha: mostly one or two actions, a few of three or four; he advises three at most. Shorten them by moving logic out of the planner: Peter Higley's Mordor orcs drew their swords as an animation transition, not a planned action.
  • Planning cost grows with the number of world-state variables. Higley folded about 40 flags that were never true together (cower and the like) into one enum and planned on about 10 variables.
  • Cap planning calls per frame. Mordor allowed up to 50 AIs to plan in a frame and did not throttle; Jacopin found one session crossing 50 calls within 0.4 s (usually 2 to 3 s) with up to 150 active NPCs. Conway plans on-screen and nearby NPCs more often than distant ones.
  • Group decisions belong to a separate role-assignment system, not every agent's goals. Mordor's investigation system takes every orc that saw a body, picks who searches (closest, a captain) and hands out roles (lead, watch his back, dismiss); each orc's planner only plans for its role. Tomb Raider lets only so many investigate and delays the event by distance, so the closest NPC plans first.

Deliberation under a frame budget

Re-plans, path batches, influence maps and procgen are slow but rarely needed: run them as C# iterators under a fixed budget per physics tick on the main thread (Ai/FrameBudget.cs), not on an unbounded Task.Run; a 20 ms search spread at 1 ms a frame answers in a third of a second, which players read as reaction time. The code, cancelling and priorities, and why a time budget is not repeatable: budget.md.

5. Steering

Steering.Seek, Flee, Arrive, Pursue, Evade, Wander, flocking (Separation, Alignment, Cohesion), FollowPath and AvoidObstacles return a velocity change; SteeringAgent.Step applies it capped at MaxForce per second. Feed agent.Velocity to CharacterBody2D.Velocity and MoveAndSlide().

  • Seek is normalize(target - position) * maxSpeed - velocity. Reynolds' 1999 paper prints the subtraction the other way round under Seek: copied, the agent flees.
  • Arrive slows inside a radius; Seek overshoots and orbits ("like a moth around a light bulb").
  • Pursuit aims at target + targetVelocity * distance / speed; it catches a crossing target sooner than Seek. That guess is fine for a body that re-steers every frame, not for a projectile, which cannot (below).
  • Wander nudges a point on a circle ahead each step; random force each frame is twitchy. Pass in a generator seeded from the run seed (procgen), not System.Random (determinism): the C# example's Wander, Aim.Scatter, PacingDirector and ResponseSystem take a DeterministicRandom.
  • Summed behaviours can cancel out; put obstacle avoidance first (the first non-zero wins) when it must not lose.

Aiming projectiles

Lead anything slow enough to dodge with Aim.Lead (the exact intercept: the smallest positive root of a quadratic; null means no shot), arc with Aim.Ballistic, and miss on purpose with Aim.Scatter (±2 degrees) or the AI is an aimbot. position + velocity * distance / speed hit 3.6% of fast targets where Aim.Lead hit 100%. Details, the designer knobs and the fallbacks: aiming.md. Losing well (Lidén's intentional mistakes, as tests): mistakes.md.

6. Perception

Perception answers "is the target there?"; what it means is the decision layer's job (Ai/Perception.cs). Test shape and range before casting a ray, sample several points on the target, see from the muzzle once the weapon is out, stack modifiers with handles, and decide from a TargetMemory, not this frame's ray, after a human reaction delay. Rules, Godot ray wiring and budgets: perception.md.

7. Navigation (Godot 4.7)

  • A path query on a map that has not synchronised returns an empty path, and the agent stands still with no error: IsNavigationFinished() is false and GetNextPathPosition() returns its own position.
  • "Await one physics frame" (the documentation's advice) is not enough on 4.7.2's defaults (asynchronous map and region iterations): a region added in _Ready gave paths only from physics frame 6 or 7, varying between identical runs. MapGetIterationId > 0 is not enough either, MapForceUpdate is obsolete, and waiting for one more MapChanged hangs when asynchronous iterations are off. Poll a real condition, with a cap:

    public static async Task<bool> WaitForNavigationReady(Node node, Rid map, Rid region, Vector2 probe, int maxFrames = 120)
    {
        for (int i = 0; i < maxFrames; i++)
        {
            if (NavigationServer2D.MapGetIterationId(map) > 0 && NavigationServer2D.MapGetClosestPointOwner(map, probe) == region)
                return true;
            await node.ToSignal(node.GetTree(), SceneTree.SignalName.PhysicsFrame);
        }
        return false;
    }

    Start it deferred (CallDeferred or _ = WaitForNavigationReady(...)), not awaited inside _Ready.

  • Set TargetPosition when the target moves meaningfully, not every frame: re-pathing each frame makes agents dance.
  • Avoidance (AvoidanceEnabled): set Velocity every physics frame and move the body in VelocityComputed. It does not change the path.
  • A path query costs about 40 µs on a 300-polygon 2D mesh; spread hundreds of agents' re-paths over frames, or give a crowd chasing one target a single Dijkstra map (algorithms).
  • Bake at run time from collision shapes or outlines; AddMesh reads meshes back from the GPU and stalls. Free the RIDs you create (NavigationServer2D.FreeRid) or they leak at exit.

Decisions that must agree

Two checks that should give one answer (navigation's "arrived" and combat's "in range"; each squad member's "am I the closest?") stop agreeing once rounding enters: the agent twitches in place or the whole squad waits. Tested in Ai/Agreement.cs; the talk behind it: ${CLAUDE_PLUGIN_ROOT}/docs/gdc/a-house-built-on-sand.md.

  • Decide once per squad, not in each member. SquadTurns.PickAttacker(target, members) measures every distance from the target the same way and gives exact ties to the lowest ID. Members deciding alone, each in its own frame, left zero or two attackers in 3,384 of 10,000 near-tie squads at (100000, 100000); a tolerance band plus an ID tiebreak still failed 1,761 times (ExactlyOneSquadMemberAttacks).
  • Arriving must mean in range. Aim the NavigationAgent2D/3D at the target itself with TargetDesiredDistance below the attack range (AttackReach.ArriveWithin), and let combat check the same distance against the range. The agent stops up to TargetDesiredDistance from TargetPosition (defaults 10 px in 2D, 1 m in 3D; 8 px short in a 4.7.2 run), so aimed at a stand point on the range circle it stops outside it. NavigationFinished with IsTargetReached() false means the path ended short (the target is off the mesh): do not re-request the same path.
  • Test AI at the largest coordinates the game uses, not only in a small level at the origin. Floats are 0.0078 apart at 100000: a stand point one unit from the target came out 1.0033 away, and Steering.Arrive froze 0.15 short of it, its last steps rounding to nothing. Tolerances that passed all 100 approaches at the origin failed all 100 there (ArrivalAndAttackRangeAgreeFarFromOrigin). float.Epsilon (1.4e-45 in C#) is never a tolerance.
  • A check tests what it means. Keep cut-scene actors out of targeting with a flag that says so, not "is playing a scripted animation": in the talk, sheathing a sword later became one and made the player untargetable. Write down what IsAlive returns during the death animation, and assert it.

8. Addons

LimboAI (MIT; behaviour trees and a hierarchical state machine, with an editor and debugger) supports C# only in its engine-module build, which means a custom editor and export templates. Beehave (MIT) is GDScript only. For a C# game on stock Godot, plain C# classes like the C# example's are the portable choice.

9. Prove it

Decision logic is plain C#: unit tests under 10 ms each, with seeded randomness. Scenario tests run in Godot (godot-test-loop), wait on conditions with a time-out, never on a fixed number of frames.

  • each structure's failure mode has a test: momentum stops flip-flopping, a higher branch interrupts and aborts, GOAP finds the cheapest plan, changes it when the situation changes its costs and gives up within its budget, arrive does not overshoot, a led shot flown frame by frame hits fast targets
  • perception: no ray for a point outside the shape, one blocked sample does not hide the target, ending one modifier keeps the others, a brief occlusion does not forget the target
  • re-plans and path batches for many agents run under a FrameBudget, tested with a fake clock, not wall time
  • a scenario test waits for navigation to be ready, then asserts the agent reaches its goal within N seconds and is never stuck (it moves more than a little over every half second)
  • every random choice comes from an injected, seeded RandomNumberGenerator (or DeterministicRandom inside a replayed simulation); the same seed gives the same run
  • decisions are recorded (frame, agent, choice, top scores) to a ring buffer the game can show when debugging
  • bench with the most agents the design allows stays inside the frame budget (performance)
  • squad choices are made once per squad; arrival and range tests also run at the game's largest coordinates

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.