94 added, 40 removed. Audit A to A.
---
name: game-ai
group: Craft
description: >-
Design NPC behaviour: behaviour trees, state machines, pathfinding, perception and difficulty
tuning. Use when designing behavior trees, state machines, or enemy AI.
---
- # Game AI
- Design NPC behaviour: behaviour trees, state machines, pathfinding, perception and difficulty tuning..
+ # game-ai
- ## Process
+ ## Core Philosophy
+ Game Artificial Intelligence (AI) is not academic machine learning trying to predict the future or beat human chess grandmasters. Game AI is an entertainment and pacing illusion. An NPC that plays with superhuman accuracy, pixel-perfect aim, and zero hesitation is frustrating and un-fun to play against. Game AI must provide clear telegraphing, readable tactical decision-making, believable sensory perception, and dynamic difficulty calibration that gives players the thrilling sensation of outsmarting a competent opponent.
- 1. **Intake & Scope Definition**
- - Identify specific objectives, inputs, constraints, and operational context.
- - Inspect existing project documentation, configurations, or relevant repository assets.
+ ---
- 2. **Analysis & Strategic Formulation**
- - Evaluate options against best practices, security posture, and domain requirements.
- - Deconstruct complex components into discrete, actionable phases.
+ ## 4-Step Game AI Architecture
- 3. **Execution & Synthesis**
- - Produce structured, production-grade deliverables matching the required format.
- - Ground all recommendations in concrete project evidence rather than abstract generalities.
+ ### Step 1: Decision-Making Architectures: Behavior Trees vs FSMs
+ 1. **Behavior Trees (The Industry Standard for Combat AI)**:
+ - Built on hierarchical nodes evaluated from left-to-right:
+ - *Composites*:
+ - **Sequence ($ o$)**: Executes children sequentially; fails if any child fails (e.g. *Has Weapon* $ o$ *Reload* $ o$ *Aim*).
+ - **Selector ($?$)**: Executes children until one succeeds (e.g. *Flee If Low Health* $?$ *Melee Attack* $?$ *Seek Cover*).
+ - *Decorators*: Conditional gates (e.g. *Invert, Time Limit, Cooldown*).
+ - *Leaves / Tasks*: Concrete executable actions (e.g. *MoveToPosition, PlayAnimation*).
+ 2. **Finite State Machines (FSMs)**:
+ - Best for simple ambient creatures or discrete bosses (States: *Patrol, Investigate, Chase, Attack, Flee*).
- 4. **Review & Refinement**
- - Validate against the verification checklist and domain edge cases.
- - Highlight open questions, explicit trade-offs, and next milestones.
+ ### Step 2: Sensory Perception Systems (Sight & Sound)
+ 1. **Vision Cones (Sight Perception)**:
+ - Evaluate target visibility using 3 gates:
+ - *Distance Check*: Is player within sight radius ($D \le R_{text{max}}$)?
+ - *Field of View Angle*: Is the dot product of enemy forward vector and direction-to-player $\ge \cos( heta / 2)$?
+ - *Line of Sight (Raycast)*: Does a physics raycast from enemy eyes to player torso hit world geometry or the player?
+ 2. **Acoustic Perception (Hearing)**:
+ - Propagate sound events through the game world (e.g. Gunshot = 40m radius; Footsteps = 8m radius).
+ - Alerted NPCs transition to an *Investigate* state directed toward the sound origin.
- ## Deliverable & Output Format
+ ### Step 3: NavMesh Pathfinding & Tactical Flanking
+ 1. **A* Pathfinding on Navigation Meshes**:
+ - NPCs query pre-baked NavMeshes for path traversal.
+ - *Reciprocal Velocity Obstacles (RVO / ORCA)*: Implement local collision avoidance so groups of 5 enemies don't march in an identical single file or jam doorway entrances.
+ 2. **Tactical Cover Finding & Flanking**:
+ - Query Environmental Query Systems (EQS): Sample candidate points around the player, score points based on cover geometry angle, distance, and line-of-sight protection.
- ### ๐ Executive Summary
- - **Objective:** Key goal addressed
- - **Status:** Complete / Action Required
- - **Primary Recommendation:** Core actionable conclusion
+ ### Step 4: Telegraphing & The Illusion of Competence
+ 1. **Telegraphing Intent**:
+ - Before executing a lethal attack, NPCs must telegraph intent through audio cues ("Flanking left!", "Grenade out!"), wind-up animations, or laser sight lines.
+ 2. **The "Stormtrooper Effect" (Controlled Incompetence)**:
+ - First shot fired at an unaware player should intentionally miss by 1 meter to alert the player and create adrenaline before dealing real damage.
- ### ๐ ๏ธ Detailed Implementation / Analysis
- - Concrete technical, operational, or strategic specifications.
- - Clear code, configuration, or documentation blocks where applicable.
+ ---
- ### ๐ Decisions & Next Steps
- - [ ] Immediate action items with designated owners.
- - [ ] Required dependencies or prerequisite milestones.
+ ## Deliverable Format: Enemy AI Behavior Tree Specification (`ENEMY-AI-SPEC.md`)
- ## Instructions & Operating Rules
+ ```markdown
+ # Combat Enemy AI Behavior Tree Specification: [NPC Archetype]
- - Lead directly with actionable findings and structured results.
- - Never introduce speculative abstractions or unrequested complexity.
- - Maintain consistency with existing architecture and naming conventions.
- - Provide explicit rationales for non-obvious trade-offs.
+ ## 1. Perception Parameters
+ - **Sight Distance**: 25 meters (Day) / 14 meters (Night)
+ - **Field of View Angle**: 110 degrees
+ - **Hearing Radius**: Gunfire = 50m | Running Footsteps = 12m | Crouch Walk = 0m (Silent)
+ - **Reaction Time Buffer**: 350ms delay between target acquisition and attack trigger
- ## Verification & Quality Checklist
+ ## 2. Master Behavior Tree Hierarchy
+ ```
+ Root (Selector)
+ โโโ [Decorator: Health < 20%] -> Sequence (Emergency Flee)
+ โ โโโ FindCoverAwayFromPlayer()
+ โ โโโ MoveToCover()
+ โ โโโ PlayAnimation("Heal")
+ โโโ [Decorator: CanSeePlayer == True] -> Selector (Combat Branch)
+ โ โโโ [Decorator: InMeleeRange] -> Sequence (Melee Strike)
+ โ โ โโโ PlayAudioBark("Charge!")
+ โ โ โโโ TelegraphWindup(400ms)
+ โ โ โโโ ExecuteMeleeDamage()
+ โ โโโ Sequence (Ranged Engagement)
+ โ โโโ Selector (Take Cover or Flank)
+ โ โ โโโ [Decorator: InCover] -> AimAtPlayer()
+ โ โ โโโ MoveToFlankPosition()
+ โ โโโ FireBurst(3_rounds)
+ โโโ Sequence (Patrol / Idle)
+ โโโ PickNextPatrolWaypoint()
+ โโโ MoveToWaypoint()
+ โโโ WaitRandom(2s, 5s)
+ ```
- - [ ] Deliverable directly satisfies all stated user requirements and criteria.
- - [ ] Edge cases, boundary conditions, and error states are addressed.
- - [ ] Output contains zero placeholder tokens, broken references, or unverified claims.
- - [ ] All cross-references and formatting comply with repository conventions.
+ ## 3. Audio Barks & Player Feedback
+ - **On Spotting Player**: *"Contact! Nine o'clock!"*
+ - **On Grenade Toss**: *"Frag out! Take cover!"*
+ ```
- ## Anti-Patterns & Constraints
+ ---
- - **NEVER** output generic boilerplate without grounding in specific project inputs.
- - **NEVER** silently omit unresolved contradictions or unverified assumptions.
- - **NEVER** make unrequested modifications outside the stated deliverable boundary.
+ ## Worked Example: Fixing "Unfair" Sniper Enemy AI
+
+ - **Problem**: Playtesters hated a sniper enemy because it instantly killed players across the map without warning.
+ - **Remediation**: Added a visible red laser sight line sweeping across the ground for 2.0 seconds before firing, paired with a distinct audio charge-up whine.
+ - **Outcome**: Player deaths felt fair and avoidable; playtest satisfaction scores jumped from 32% to 88%.
+
+ ---
+
+ ## Verification Checklist
+
+ - [ ] Perception system validates distance, FOV cone, and physics raycast line-of-sight.
+ - [ ] Behavior tree prioritizes survival/flee states before offensive actions.
+ - [ ] All lethal attacks include readable telegraphing animations or audio barks.
+ - [ ] NavMesh agents implement local avoidance (RVO) to prevent doorway crowding.
+ - [ ] Enemy reaction times include realistic human-like delay buffers (200โ400ms).
+
+ ---
+
+ ## Anti-Patterns
+
+ - **Omniscient AI**: Letting enemies know player coordinates through solid walls without perception checks.
+ - **Frame-Zero Snapping**: Enemies pivoting $180^\circ$ and firing with 100% accuracy in a single frame.
+ - **The Single-File Lemmings**: Having 8 enemies march in a straight line through a single hallway to be slaughtered one by one.