[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7E6GN3ASA8V8Q10WRPWB7W8":3,"skill-same:01M7E6GN3ASA8V8Q10WRPWB7W8":69},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":6,"updatedAt":32,"install":33,"resources":46},"01M7E6GN3ASA8V8Q10WRPWB7W8","game-ai",null,"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.","nick-vas\u002Fhyperdot","nick-vas","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F7181961?v=4","01M7E6F6F0BQ49V0JZHX9BXCBD","Nikolaos Vasilikiotis","01M7E6F6FZW8SW1AJ1S7ARFE89",1,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fnick-vas\u002Fhyperdot\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgame-ai\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: game-ai\ndescription: 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.\n---\n\n# Game AI in Godot 4 (C#)\n\nPick the simplest decision structure that holds, keep it in plain C# so it is tested without the engine, and wait for\nnavigation before trusting a path. Tested implementations: `${CLAUDE_PLUGIN_ROOT}\u002Fexamples\u002Fcsharp\u002Fsrc\u002FExample.Core\u002FAi\u002F`\n(`Utility.cs`, `BehaviorTree.cs`, `Goap.cs`, `Steering.cs`, `Aim.cs`, `Perception.cs`) with\n`${CLAUDE_PLUGIN_ROOT}\u002Fexamples\u002Fcsharp\u002Ftests\u002FExample.Core.Tests\u002FAiTests.cs` and `AimTests.cs`. Sources and measurements:\n`${CLAUDE_PLUGIN_ROOT}\u002Fdocs\u002Fgame-ai.md`.\n\n## 1. Which structure\n\n| Structure | Fits | Breaks when | Watch for |\n|---|---|---|---|\n| State machine | 3 to 8 states with clear transitions: patrol, chase, attack; doors; boss phases | One 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 |\n| Hierarchical state machine | Modes with sub-modes; an interruption that must resume where it was (a history state) | Priorities change with context | |\n| Behaviour tree | Priority-ordered, reactive behaviour that designers read: combat, squad roles | Tens of float priorities among siblings (Halo 2 made relevance yes or no for this reason) | A selector that never interrupts a running lower branch |\n| Utility AI | Many close options: tactics, needs (The Sims), RPG choices, economy | Scores nobody can explain | Flip-flopping between two near-equal actions |\n| GOAP | Many character types sharing goals with different action sets; multi-step plans nobody wired (F.E.A.R.) | The search costs more than the frame | Replanning every frame; forward search |\n| HTN | Designer-written multi-step behaviour with priorities by method order | Plans the designer did not foresee are needed | Replanning on the plan's own effects cancels deliberate steps |\n\nStart with a state machine; move up when its failure mode appears, not before. F.E.A.R.'s soldiers ran a state machine of\nthree states (go to, animate, use object) with a planner choosing what to put in them. When enemies come (not how strong):\nLeft 4 Dead's director, `PacingDirector` (`docs\u002Fvalve.md` 4).\n\n## 2. Behaviour trees\n\n- Composites re-evaluate from the first child every tick, so a higher-priority branch interrupts at once, and the branch\n  it interrupts is told (`Abort`): stop the animation, release the cover point, clear the path. The C# example's `Selector` and\n  `Sequence` do this; a \"passive\" selector that only resumes the running child does not react.\n- Every long action handles abort. Abrupt aborts have side effects: a reload interrupted half-way needs a rule.\n- Keep leaves small and data in the context object, not a stringly-typed blackboard for everything.\n- A tree runs a decided behaviour; a state machine above it switches modes. Retries, cooldowns, utility logs, disabled\n  data: [pitfalls.md](pitfalls.md).\n\n## 3. Utility AI\n\n- Each consideration maps one fact, scaled to 0..1, through a response curve (`Curves.Linear`, `Power`, `Logistic`,\n  `Inverted`); an action's score is the product, so any consideration at 0 vetoes it. Products shrink with more factors:\n  `UtilityAction.Score` compensates (Dave Mark's makeup factor) so an action that checks four things is not punished.\n- Weights rank groups: 1 for normal actions, 2 or more for emergencies (flee, heal).\n- Momentum against dithering: two actions at 0.5 with ±10% noise switched 502 times in 1000 ticks with no bonus and 0\n  times with 25% (`UtilitySelector(..., momentum: 0.25f)`). Keep the bonus above the noise; pair it with a cooldown\n  consideration, or commit until the action ends, so real changes still win.\n- Log `LastScores` per decision: \"why did it do that\" is answered from the numbers.\n\n## 4. GOAP\n\n- Actions declare preconditions, effects and a cost; `GoapPlanner.Plan(state, goal, actions)` searches backwards from\n  the goal, so actions irrelevant to it cost nothing. A forward search took 110 ms and gave up on a six-step plan hidden\n  among 20 cheap irrelevant actions; backward, it plans in microseconds.\n- Cap the search (`maxExpanded`) and treat `null` as \"no plan\": fall back to a default behaviour. `Plan(..., out int expanded)`\n  reports the work done; assert on it, not on wall time, which fails under load.\n- Replan on events (the goal changed, the plan failed or was invalidated), not every frame and not on the plan's own\n  effects. F.E.A.R. kept one goal active at a time and spread expensive checks across frames as cached facts.\n- Checks that cost (line of sight, a path) belong in the action's run-time check, not the world state.\n- Price actions from the situation instead of writing range rules: `GoapPlanner.Plan(state, goal, actions, costOf: a => ...)`\n  with walking costing the distance. Chris Conway's Tomb Raider example: 20 m away, melee 1 + walk 20 = 21 loses to\n  ranged 10 + walk 1, and out of ammo the same actions run in to melee with no rule to change (`GoapCostsFollowTheSituation`).\n- 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\n  or two actions, a few of three or four; he advises three at most. Shorten them by moving logic out of the planner:\n  Peter Higley's Mordor orcs drew their swords as an animation transition, not a planned action.\n- Planning cost grows with the number of world-state variables. Higley folded about 40 flags that were never true\n  together (cower and the like) into one enum and planned on about 10 variables.\n- Cap planning calls per frame. Mordor allowed up to 50 AIs to plan in a frame and did not throttle; Jacopin found one\n  session crossing 50 calls within 0.4 s (usually 2 to 3 s) with up to 150 active NPCs. Conway plans on-screen and\n  nearby NPCs more often than distant ones.\n- Group decisions belong to a separate role-assignment system, not every agent's goals. Mordor's investigation system\n  takes every orc that saw a body, picks who searches (closest, a captain) and hands out roles (lead, watch his back,\n  dismiss); each orc's planner only plans for its role. Tomb Raider lets only so many investigate and delays the event\n  by distance, so the closest NPC plans first.\n\n### Deliberation under a frame budget\n\nRe-plans, path batches, influence maps and procgen are slow but rarely needed: run them as C# iterators under a fixed\nbudget per physics tick on the main thread (`Ai\u002FFrameBudget.cs`), not on an unbounded `Task.Run`; a 20 ms search spread\nat 1 ms a frame answers in a third of a second, which players read as reaction time. The code, cancelling and\npriorities, and why a time budget is not repeatable: [budget.md](budget.md).\n\n## 5. Steering\n\n`Steering.Seek`, `Flee`, `Arrive`, `Pursue`, `Evade`, `Wander`, flocking (`Separation`, `Alignment`, `Cohesion`), `FollowPath`\nand `AvoidObstacles` return a velocity change; `SteeringAgent.Step`\napplies it capped at `MaxForce` per second. Feed `agent.Velocity` to `CharacterBody2D.Velocity` and `MoveAndSlide()`.\n\n- Seek is `normalize(target - position) * maxSpeed - velocity`. Reynolds' 1999 paper prints the subtraction the other way\n  round under Seek: copied, the agent flees.\n- Arrive slows inside a radius; Seek overshoots and orbits (\"like a moth around a light bulb\").\n- Pursuit aims at `target + targetVelocity * distance \u002F speed`; it catches a crossing target sooner than Seek. That guess\n  is fine for a body that re-steers every frame, not for a projectile, which cannot (below).\n- 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`.\n- Summed behaviours can cancel out; put obstacle avoidance first (the first non-zero wins) when it must not lose.\n\n### Aiming projectiles\n\nLead anything slow enough to dodge with `Aim.Lead` (the exact intercept: the smallest positive root of a quadratic; null\nmeans no shot), arc with `Aim.Ballistic`, and miss on purpose with `Aim.Scatter` (±2 degrees) or the AI is an aimbot.\n`position + velocity * distance \u002F speed` hit 3.6% of fast targets where `Aim.Lead` hit 100%. Details, the designer knobs\nand the fallbacks: [aiming.md](aiming.md). Losing well (Lidén's intentional mistakes, as tests): [mistakes.md](mistakes.md).\n\n## 6. Perception\n\nPerception answers \"is the target there?\"; what it means is the decision layer's job (`Ai\u002FPerception.cs`). Test shape and\nrange before casting a ray, sample several points on the target, see from the muzzle once the weapon is out, stack\nmodifiers with handles, and decide from a `TargetMemory`, not this frame's ray, after a human reaction delay. Rules,\nGodot ray wiring and budgets: [perception.md](perception.md).\n\n## 7. Navigation (Godot 4.7)\n\n- A path query on a map that has not synchronised returns an empty path, and the agent stands still with no error:\n  `IsNavigationFinished()` is false and `GetNextPathPosition()` returns its own position.\n- \"Await one physics frame\" (the documentation's advice) is not enough on 4.7.2's defaults (asynchronous map and region\n  iterations): a region added in `_Ready` gave paths only from physics frame 6 or 7, varying between identical runs.\n  `MapGetIterationId > 0` is not enough either, `MapForceUpdate` is obsolete, and waiting for one more `MapChanged` hangs\n  when asynchronous iterations are off. Poll a real condition, with a cap:\n\n  ```csharp\n  public static async Task\u003Cbool> WaitForNavigationReady(Node node, Rid map, Rid region, Vector2 probe, int maxFrames = 120)\n  {\n      for (int i = 0; i \u003C maxFrames; i++)\n      {\n          if (NavigationServer2D.MapGetIterationId(map) > 0 && NavigationServer2D.MapGetClosestPointOwner(map, probe) == region)\n              return true;\n          await node.ToSignal(node.GetTree(), SceneTree.SignalName.PhysicsFrame);\n      }\n      return false;\n  }\n  ```\n\n  Start it deferred (`CallDeferred` or `_ = WaitForNavigationReady(...)`), not awaited inside `_Ready`.\n- Set `TargetPosition` when the target moves meaningfully, not every frame: re-pathing each frame makes agents dance.\n- Avoidance (`AvoidanceEnabled`): set `Velocity` every physics frame and move the body in `VelocityComputed`. It does\n  not change the path.\n- A path query costs about 40 µs on a 300-polygon 2D mesh; spread hundreds of agents' re-paths over frames, or give a\n  crowd chasing one target a single Dijkstra map (`algorithms`).\n- Bake at run time from collision shapes or outlines; `AddMesh` reads meshes back from the GPU and stalls. Free the RIDs\n  you create (`NavigationServer2D.FreeRid`) or they leak at exit.\n\n### Decisions that must agree\n\nTwo checks that should give one answer (navigation's \"arrived\" and combat's \"in range\"; each squad member's \"am I the\nclosest?\") stop agreeing once rounding enters: the agent twitches in place or the whole squad waits. Tested in\n`Ai\u002FAgreement.cs`; the talk behind it: `${CLAUDE_PLUGIN_ROOT}\u002Fdocs\u002Fgdc\u002Fa-house-built-on-sand.md`.\n\n- Decide once per squad, not in each member. `SquadTurns.PickAttacker(target, members)` measures every distance from\n  the target the same way and gives exact ties to the lowest ID. Members deciding alone, each in its own frame, left\n  zero or two attackers in 3,384 of 10,000 near-tie squads at (100000, 100000); a tolerance band plus an ID tiebreak\n  still failed 1,761 times (`ExactlyOneSquadMemberAttacks`).\n- Arriving must mean in range. Aim the `NavigationAgent2D`\u002F`3D` at the target itself with `TargetDesiredDistance`\n  below the attack range (`AttackReach.ArriveWithin`), and let combat check the same distance against the range. The\n  agent stops up to `TargetDesiredDistance` from `TargetPosition` (defaults 10 px in 2D, 1 m in 3D; 8 px short in a\n  4.7.2 run), so aimed at a stand point on the range circle it stops outside it. `NavigationFinished` with\n  `IsTargetReached()` false means the path ended short (the target is off the mesh): do not re-request the same path.\n- Test AI at the largest coordinates the game uses, not only in a small level at the origin. Floats are 0.0078 apart at\n  100000: a stand point one unit from the target came out 1.0033 away, and `Steering.Arrive` froze 0.15 short of it,\n  its last steps rounding to nothing. Tolerances that passed all 100 approaches at the origin failed all 100 there\n  (`ArrivalAndAttackRangeAgreeFarFromOrigin`). `float.Epsilon` (1.4e-45 in C#) is never a tolerance.\n- A check tests what it means. Keep cut-scene actors out of targeting with a flag that says so, not \"is playing a\n  scripted animation\": in the talk, sheathing a sword later became one and made the player untargetable. Write down\n  what `IsAlive` returns during the death animation, and assert it.\n\n## 8. Addons\n\nLimboAI (MIT; behaviour trees and a hierarchical state machine, with an editor and debugger) supports C# only in its\nengine-module build, which means a custom editor and export templates. Beehave (MIT) is GDScript only. For a C# game on\nstock Godot, plain C# classes like the C# example's are the portable choice.\n\n## 9. Prove it\n\nDecision logic is plain C#: unit tests under 10 ms each, with seeded randomness. Scenario tests run in Godot\n(`godot-test-loop`), wait on conditions with a time-out, never on a fixed number of frames.\n\n- [ ] each structure's failure mode has a test: momentum stops flip-flopping, a higher branch interrupts and aborts,\n      GOAP finds the cheapest plan, changes it when the situation changes its costs and gives up within its budget,\n      arrive does not overshoot, a led shot flown frame by frame hits fast targets\n- [ ] perception: no ray for a point outside the shape, one blocked sample does not hide the target, ending one\n      modifier keeps the others, a brief occlusion does not forget the target\n- [ ] re-plans and path batches for many agents run under a `FrameBudget`, tested with a fake clock, not wall time\n- [ ] a scenario test waits for navigation to be ready, then asserts the agent reaches its goal within N seconds and is\n      never stuck (it moves more than a little over every half second)\n- [ ] every random choice comes from an injected, seeded `RandomNumberGenerator` (or `DeterministicRandom` inside a\n      replayed simulation); the same seed gives the same run\n- [ ] decisions are recorded (frame, agent, choice, top scores) to a ring buffer the game can show when debugging\n- [ ] `bench` with the most agents the design allows stays inside the frame budget (`performance`)\n- [ ] squad choices are made once per squad; arrival and range tests also run at the game's largest coordinates\n","# Game AI in Godot 4 (C#)\n\nPick the simplest decision structure that holds, keep it in plain C# so it is tested without the engine, and wait for\nnavigation before trusting a path. Tested implementations: `${CLAUDE_PLUGIN_ROOT}\u002Fexamples\u002Fcsharp\u002Fsrc\u002FExample.Core\u002FAi\u002F`\n(`Utility.cs`, `BehaviorTree.cs`, `Goap.cs`, `Steering.cs`, `Aim.cs`, `Perception.cs`) with\n`${CLAUDE_PLUGIN_ROOT}\u002Fexamples\u002Fcsharp\u002Ftests\u002FExample.Core.Tests\u002FAiTests.cs` and `AimTests.cs`. Sources and measurements:\n`${CLAUDE_PLUGIN_ROOT}\u002Fdocs\u002Fgame-ai.md`.\n\n## 1. Which structure\n\n| Structure | Fits | Breaks when | Watch for |\n|---|---|---|---|\n| State machine | 3 to 8 states with clear transitions: patrol, chase, attack; doors; boss phases | One 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 |\n| Hierarchical state machine | Modes with sub-modes; an interruption that must resume where it was (a history state) | Priorities change with context | |\n| Behaviour tree | Priority-ordered, reactive behaviour that designers read: combat, squad roles | Tens of float priorities among siblings (Halo 2 made relevance yes or no for this reason) | A selector that never interrupts a running lower branch |\n| Utility AI | Many close options: tactics, needs (The Sims), RPG choices, economy | Scores nobody can explain | Flip-flopping between two near-equal actions |\n| GOAP | Many character types sharing goals with different action sets; multi-step plans nobody wired (F.E.A.R.) | The search costs more than the frame | Replanning every frame; forward search |\n| HTN | Designer-written multi-step behaviour with priorities by method order | Plans the designer did not foresee are needed | Replanning on the plan's own effects cancels deliberate steps |\n\nStart with a state machine; move up when its failure mode appears, not before. F.E.A.R.'s soldiers ran a state machine of\nthree states (go to, animate, use object) with a planner choosing what to put in them. When enemies come (not how strong):\nLeft 4 Dead's director, `PacingDirector` (`docs\u002Fvalve.md` 4).\n\n## 2. Behaviour trees\n\n- Composites re-evaluate from the first child every tick, so a higher-priority branch interrupts at once, and the branch\n  it interrupts is told (`Abort`): stop the animation, release the cover point, clear the path. The C# example's `Selector` and\n  `Sequence` do this; a \"passive\" selector that only resumes the running child does not react.\n- Every long action handles abort. Abrupt aborts have side effects: a reload interrupted half-way needs a rule.\n- Keep leaves small and data in the context object, not a stringly-typed blackboard for everything.\n- A tree runs a decided behaviour; a state machine above it switches modes. Retries, cooldowns, utility logs, disabled\n  data: [pitfalls.md](pitfalls.md).\n\n## 3. Utility AI\n\n- Each consideration maps one fact, scaled to 0..1, through a response curve (`Curves.Linear`, `Power`, `Logistic`,\n  `Inverted`); an action's score is the product, so any consideration at 0 vetoes it. Products shrink with more factors:\n  `UtilityAction.Score` compensates (Dave Mark's makeup factor) so an action that checks four things is not punished.\n- Weights rank groups: 1 for normal actions, 2 or more for emergencies (flee, heal).\n- Momentum against dithering: two actions at 0.5 with ±10% noise switched 502 times in 1000 ticks with no bonus and 0\n  times with 25% (`UtilitySelector(..., momentum: 0.25f)`). Keep the bonus above the noise; pair it with a cooldown\n  consideration, or commit until the action ends, so real changes still win.\n- Log `LastScores` per decision: \"why did it do that\" is answered from the numbers.\n\n## 4. GOAP\n\n- Actions declare preconditions, effects and a cost; `GoapPlanner.Plan(state, goal, actions)` searches backwards from\n  the goal, so actions irrelevant to it cost nothing. A forward search took 110 ms and gave up on a six-step plan hidden\n  among 20 cheap irrelevant actions; backward, it plans in microseconds.\n- Cap the search (`maxExpanded`) and treat `null` as \"no plan\": fall back to a default behaviour. `Plan(..., out int expanded)`\n  reports the work done; assert on it, not on wall time, which fails under load.\n- Replan on events (the goal changed, the plan failed or was invalidated), not every frame and not on the plan's own\n  effects. F.E.A.R. kept one goal active at a time and spread expensive checks across frames as cached facts.\n- Checks that cost (line of sight, a path) belong in the action's run-time check, not the world state.\n- Price actions from the situation instead of writing range rules: `GoapPlanner.Plan(state, goal, actions, costOf: a => ...)`\n  with walking costing the distance. Chris Conway's Tomb Raider example: 20 m away, melee 1 + walk 20 = 21 loses to\n  ranged 10 + walk 1, and out of ammo the same actions run in to melee with no rule to change (`GoapCostsFollowTheSituation`).\n- 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\n  or two actions, a few of three or four; he advises three at most. Shorten them by moving logic out of the planner:\n  Peter Higley's Mordor orcs drew their swords as an animation transition, not a planned action.\n- Planning cost grows with the number of world-state variables. Higley folded about 40 flags that were never true\n  together (cower and the like) into one enum and planned on about 10 variables.\n- Cap planning calls per frame. Mordor allowed up to 50 AIs to plan in a frame and did not throttle; Jacopin found one\n  session crossing 50 calls within 0.4 s (usually 2 to 3 s) with up to 150 active NPCs. Conway plans on-screen and\n  nearby NPCs more often than distant ones.\n- Group decisions belong to a separate role-assignment system, not every agent's goals. Mordor's investigation system\n  takes every orc that saw a body, picks who searches (closest, a captain) and hands out roles (lead, watch his back,\n  dismiss); each orc's planner only plans for its role. Tomb Raider lets only so many investigate and delays the event\n  by distance, so the closest NPC plans first.\n\n### Deliberation under a frame budget\n\nRe-plans, path batches, influence maps and procgen are slow but rarely needed: run them as C# iterators under a fixed\nbudget per physics tick on the main thread (`Ai\u002FFrameBudget.cs`), not on an unbounded `Task.Run`; a 20 ms search spread\nat 1 ms a frame answers in a third of a second, which players read as reaction time. The code, cancelling and\npriorities, and why a time budget is not repeatable: [budget.md](budget.md).\n\n## 5. Steering\n\n`Steering.Seek`, `Flee`, `Arrive`, `Pursue`, `Evade`, `Wander`, flocking (`Separation`, `Alignment`, `Cohesion`), `FollowPath`\nand `AvoidObstacles` return a velocity change; `SteeringAgent.Step`\napplies it capped at `MaxForce` per second. Feed `agent.Velocity` to `CharacterBody2D.Velocity` and `MoveAndSlide()`.\n\n- Seek is `normalize(target - position) * maxSpeed - velocity`. Reynolds' 1999 paper prints the subtraction the other way\n  round under Seek: copied, the agent flees.\n- Arrive slows inside a radius; Seek overshoots and orbits (\"like a moth around a light bulb\").\n- Pursuit aims at `target + targetVelocity * distance \u002F speed`; it catches a crossing target sooner than Seek. That guess\n  is fine for a body that re-steers every frame, not for a projectile, which cannot (below).\n- 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`.\n- Summed behaviours can cancel out; put obstacle avoidance first (the first non-zero wins) when it must not lose.\n\n### Aiming projectiles\n\nLead anything slow enough to dodge with `Aim.Lead` (the exact intercept: the smallest positive root of a quadratic; null\nmeans no shot), arc with `Aim.Ballistic`, and miss on purpose with `Aim.Scatter` (±2 degrees) or the AI is an aimbot.\n`position + velocity * distance \u002F speed` hit 3.6% of fast targets where `Aim.Lead` hit 100%. Details, the designer knobs\nand the fallbacks: [aiming.md](aiming.md). Losing well (Lidén's intentional mistakes, as tests): [mistakes.md](mistakes.md).\n\n## 6. Perception\n\nPerception answers \"is the target there?\"; what it means is the decision layer's job (`Ai\u002FPerception.cs`). Test shape and\nrange before casting a ray, sample several points on the target, see from the muzzle once the weapon is out, stack\nmodifiers with handles, and decide from a `TargetMemory`, not this frame's ray, after a human reaction delay. Rules,\nGodot ray wiring and budgets: [perception.md](perception.md).\n\n## 7. Navigation (Godot 4.7)\n\n- A path query on a map that has not synchronised returns an empty path, and the agent stands still with no error:\n  `IsNavigationFinished()` is false and `GetNextPathPosition()` returns its own position.\n- \"Await one physics frame\" (the documentation's advice) is not enough on 4.7.2's defaults (asynchronous map and region\n  iterations): a region added in `_Ready` gave paths only from physics frame 6 or 7, varying between identical runs.\n  `MapGetIterationId > 0` is not enough either, `MapForceUpdate` is obsolete, and waiting for one more `MapChanged` hangs\n  when asynchronous iterations are off. Poll a real condition, with a cap:\n\n  ```csharp\n  public static async Task\u003Cbool> WaitForNavigationReady(Node node, Rid map, Rid region, Vector2 probe, int maxFrames = 120)\n  {\n      for (int i = 0; i \u003C maxFrames; i++)\n      {\n          if (NavigationServer2D.MapGetIterationId(map) > 0 && NavigationServer2D.MapGetClosestPointOwner(map, probe) == region)\n              return true;\n          await node.ToSignal(node.GetTree(), SceneTree.SignalName.PhysicsFrame);\n      }\n      return false;\n  }\n  ```\n\n  Start it deferred (`CallDeferred` or `_ = WaitForNavigationReady(...)`), not awaited inside `_Ready`.\n- Set `TargetPosition` when the target moves meaningfully, not every frame: re-pathing each frame makes agents dance.\n- Avoidance (`AvoidanceEnabled`): set `Velocity` every physics frame and move the body in `VelocityComputed`. It does\n  not change the path.\n- A path query costs about 40 µs on a 300-polygon 2D mesh; spread hundreds of agents' re-paths over frames, or give a\n  crowd chasing one target a single Dijkstra map (`algorithms`).\n- Bake at run time from collision shapes or outlines; `AddMesh` reads meshes back from the GPU and stalls. Free the RIDs\n  you create (`NavigationServer2D.FreeRid`) or they leak at exit.\n\n### Decisions that must agree\n\nTwo checks that should give one answer (navigation's \"arrived\" and combat's \"in range\"; each squad member's \"am I the\nclosest?\") stop agreeing once rounding enters: the agent twitches in place or the whole squad waits. Tested in\n`Ai\u002FAgreement.cs`; the talk behind it: `${CLAUDE_PLUGIN_ROOT}\u002Fdocs\u002Fgdc\u002Fa-house-built-on-sand.md`.\n\n- Decide once per squad, not in each member. `SquadTurns.PickAttacker(target, members)` measures every distance from\n  the target the same way and gives exact ties to the lowest ID. Members deciding alone, each in its own frame, left\n  zero or two attackers in 3,384 of 10,000 near-tie squads at (100000, 100000); a tolerance band plus an ID tiebreak\n  still failed 1,761 times (`ExactlyOneSquadMemberAttacks`).\n- Arriving must mean in range. Aim the `NavigationAgent2D`\u002F`3D` at the target itself with `TargetDesiredDistance`\n  below the attack range (`AttackReach.ArriveWithin`), and let combat check the same distance against the range. The\n  agent stops up to `TargetDesiredDistance` from `TargetPosition` (defaults 10 px in 2D, 1 m in 3D; 8 px short in a\n  4.7.2 run), so aimed at a stand point on the range circle it stops outside it. `NavigationFinished` with\n  `IsTargetReached()` false means the path ended short (the target is off the mesh): do not re-request the same path.\n- Test AI at the largest coordinates the game uses, not only in a small level at the origin. Floats are 0.0078 apart at\n  100000: a stand point one unit from the target came out 1.0033 away, and `Steering.Arrive` froze 0.15 short of it,\n  its last steps rounding to nothing. Tolerances that passed all 100 approaches at the origin failed all 100 there\n  (`ArrivalAndAttackRangeAgreeFarFromOrigin`). `float.Epsilon` (1.4e-45 in C#) is never a tolerance.\n- A check tests what it means. Keep cut-scene actors out of targeting with a flag that says so, not \"is playing a\n  scripted animation\": in the talk, sheathing a sword later became one and made the player untargetable. Write down\n  what `IsAlive` returns during the death animation, and assert it.\n\n## 8. Addons\n\nLimboAI (MIT; behaviour trees and a hierarchical state machine, with an editor and debugger) supports C# only in its\nengine-module build, which means a custom editor and export templates. Beehave (MIT) is GDScript only. For a C# game on\nstock Godot, plain C# classes like the C# example's are the portable choice.\n\n## 9. Prove it\n\nDecision logic is plain C#: unit tests under 10 ms each, with seeded randomness. Scenario tests run in Godot\n(`godot-test-loop`), wait on conditions with a time-out, never on a fixed number of frames.\n\n- [ ] each structure's failure mode has a test: momentum stops flip-flopping, a higher branch interrupts and aborts,\n      GOAP finds the cheapest plan, changes it when the situation changes its costs and gives up within its budget,\n      arrive does not overshoot, a led shot flown frame by frame hits fast targets\n- [ ] perception: no ray for a point outside the shape, one blocked sample does not hide the target, ending one\n      modifier keeps the others, a brief occlusion does not forget the target\n- [ ] re-plans and path batches for many agents run under a `FrameBudget`, tested with a fake clock, not wall time\n- [ ] a scenario test waits for navigation to be ready, then asserts the agent reaches its goal within N seconds and is\n      never stuck (it moves more than a little over every half second)\n- [ ] every random choice comes from an injected, seeded `RandomNumberGenerator` (or `DeterministicRandom` inside a\n      replayed simulation); the same seed gives the same run\n- [ ] decisions are recorded (frame, agent, choice, top scores) to a ring buffer the game can show when debugging\n- [ ] `bench` with the most agents the design allows stays inside the frame budget (`performance`)\n- [ ] squad choices are made once per squad; arrival and range tests also run at the game's largest coordinates\n",{"name":5,"description":7},"main","5fa4c2262d814d50f72198a95b8c483ff195f90f",".agents\u002Fskills\u002Fgame-ai",0,"https:\u002F\u002Fgithub.com\u002Fnick-vas\u002Fhyperdot","https:\u002F\u002Fnick-vas.github.io\u002Fhyperdot\u002F","https:\u002F\u002Fgithub.com\u002Fnick-vas","https:\u002F\u002Fcommon-beef.itch.io\u002F","2026-11-13 18:55:29",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add nick-vas\u002Fhyperdot --skill game-ai",{"tool":39,"command":40},"bunx","bunx skills add nick-vas\u002Fhyperdot --skill game-ai",{"tool":42,"command":43},"pnpm","pnpm dlx skills add nick-vas\u002Fhyperdot --skill game-ai","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fnick-vas\u002Fhyperdot\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgame-ai\u002FSKILL.md",true,[47,53,57,61,65],{"path":48,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":51,"sourceHtmlUrl":52},"aiming.md","REFERENCE","参考文档",2522,"https:\u002F\u002Fgithub.com\u002Fnick-vas\u002Fhyperdot\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgame-ai\u002Faiming.md",{"path":54,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":55,"sourceHtmlUrl":56},"budget.md",2078,"https:\u002F\u002Fgithub.com\u002Fnick-vas\u002Fhyperdot\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgame-ai\u002Fbudget.md",{"path":58,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":59,"sourceHtmlUrl":60},"mistakes.md",3982,"https:\u002F\u002Fgithub.com\u002Fnick-vas\u002Fhyperdot\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgame-ai\u002Fmistakes.md",{"path":62,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":63,"sourceHtmlUrl":64},"perception.md",4819,"https:\u002F\u002Fgithub.com\u002Fnick-vas\u002Fhyperdot\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgame-ai\u002Fperception.md",{"path":66,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":67,"sourceHtmlUrl":68},"pitfalls.md",3942,"https:\u002F\u002Fgithub.com\u002Fnick-vas\u002Fhyperdot\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgame-ai\u002Fpitfalls.md",[70,77,83,90,97,104],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M7E6RF2S03S92PB9RZB4S4W0","over-budget","Use when a fixture exceeds the size budget.","https:\u002F\u002Fgithub.com\u002Fnick-vas\u002Fhyperdot\u002Fblob\u002Fmain\u002Ftests\u002Fskill-fixtures\u002Fover-budget\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M7E6RBY8SDNMA3ZARE8MAH0G","bad-yaml","https:\u002F\u002Fgithub.com\u002Fnick-vas\u002Fhyperdot\u002Fblob\u002Fmain\u002Ftests\u002Fskill-fixtures\u002Fbad-yaml\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M7E6R9S9YHTC552SR41RQAJ1","bad-workflow-description","Use when testing; runs the kit and then reads the JSON.","https:\u002F\u002Fgithub.com\u002Fnick-vas\u002Fhyperdot\u002Fblob\u002Fmain\u002Ftests\u002Fskill-fixtures\u002Fbad-workflow-description\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M7E6R6CWSAN48C80130CM1AK","bad-version","Use when a fixture quotes a stale package version.","https:\u002F\u002Fgithub.com\u002Fnick-vas\u002Fhyperdot\u002Fblob\u002Fmain\u002Ftests\u002Fskill-fixtures\u002Fbad-version\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":19},"01M7E6R2C0E24TC133ESHKZT9R","bad-value","Use when a fixture passes a value outside a parameter's set.","https:\u002F\u002Fgithub.com\u002Fnick-vas\u002Fhyperdot\u002Fblob\u002Fmain\u002Ftests\u002Fskill-fixtures\u002Fbad-value\u002FSKILL.md",[],[],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":19},"01M7E6QYM81V061X7DSQ94CZRP","bad-trigger","Helps with Godot tests.","https:\u002F\u002Fgithub.com\u002Fnick-vas\u002Fhyperdot\u002Fblob\u002Fmain\u002Ftests\u002Fskill-fixtures\u002Fbad-trigger\u002FSKILL.md",[],[]]