AI NPC Behavior System Engineering Case Study

A WebGL-ready Unity AI gameplay prototype showcasing adaptive NPC behavior using finite state machines, NavMesh pathfinding, line-of-sight detection, hearing systems, and aggression-based decision making.

Unity 6 URP
C#
Unity Input System
NavMeshAgent
NavMeshSurface
TextMeshPro

Load Interactive Demo

Click to initialize the WebGL engine (~15MB). Best experienced on desktop.

Live WebGL Instance Running

Click inside to lock mouse • Esc to unlock

System Overview

This architecture defines a lightweight, highly decoupled AI system designed to operate efficiently within WebGL constraints while providing emergent, responsive behavior. The environment consists of a single player and a dynamic NPC agent.

The core logic loop monitors a hearing radius, vision cone, and environmental line-of-sight checks. Depending on the player's aggression (calculated via DPS) and the NPC's remaining health, the system transitions between sweeping search behaviors, aggressive combat pursuit, and tactical retreats.

Animated Unity WebGL demo showing AI NPC patrol, chase, and attack behavior

Core Constraints

PlatformWebGL 2.0
Memory Target< 50 MB RAM
Logic FrequencyStaggered Coroutines

AI Decision Flow

Input

Player Tracker

Sensor

Perception System

Brain

NPC FSM Core

Motor

NavMesh / Combat

Finite State Machine (FSM)

The NPC's logic is governed by a strict hierarchical state machine. This prevents conflicting behaviors (e.g., trying to shoot while retreating) and makes debugging highly deterministic.

Patrol_State

Generates random waypoints on the NavMesh. Moves at walking speed. Transitions to Chase upon visual/audio detection.

Chase_State

Increases speed to running. Continually updates destination to Player position. Transitions to Attack when within range.

Attack_State

Halts movement. Engages combat systems. Checks Line of Sight before firing. Transitions back to Chase if player breaks LOS.

Retreat_State

Triggered by low health or high player aggression. Calculates escape vectors away from player position.

Search_State

Triggered when losing the player. Moves to last known location and rotates to scan area before returning to Patrol.

Perception System

Environmental awareness is decoupled from the Brain. The Sensor module runs staggered spatial queries to prevent Physics frame-drops.

  • 1

    Hearing Sphere (Radius: 2m)

    OverlapSphere detects player movement regardless of obstacles if they are sprinting too close.

  • 2

    Vision Cone (Angle: 110°, Range: 8m)

    Dot product calculation verifies if the player is within the forward frustum of the NPC.

  • 3

    Line of Sight (Physics.Linecast)

    A final raycast ensures walls/obstacles block vision before triggering a confirmed detection.

AI NPC in patrol state inside Unity WebGL arena

FOV_SIMULATION_ACTIVE

Combat System

The combat loop utilizes a LineRenderer for visual feedback, bypassing the need for expensive projectile instantiations in WebGL.

When the NPC enters the Attack State, it halts the NavMeshAgent, smoothly rotates to face the player, and checks an un-obstructed Line of Sight. If clear, it applies instant raycast damage and triggers a knockback force to the player's Rigidbody.

AI NPC attacking player in Unity behavior system demo

LASER_COOLDOWN_ROUTINE

Data Ownership Architecture

To maintain a clean architecture, data flows in a single direction. The UI components only read data via events, and the Brain only reacts to data injected by the Sensors.

Data / StateSource / OwnerObserver
CurrentStateNPCBrainNPCDebugUI
AggressionScorePlayerBehaviorTrackerNPCBrain
PlayerLocationNPCSensorNPCMotor (NavMesh)
HealthHealthSystemNPCBrain / UI

Editor Automation Pipeline

For rapid iteration, I built an Editor Script: AINPCLabBuilder.cs. This tool adds a custom dropdown to the Unity Editor toolbar allowing for one-click environment generation.

Automated NavMesh Baking
Layer / Tag Validation
WebGL Build Preset Config
Brotli Compression Validation

Performance Metrics

~20

Draw Calls

<50KB

NavMesh Data

60

Stable FPS

Yes

IL2CPP Opt

Architectural Decisions

FSM over Behavior Trees: For a single NPC agent with highly predictable states, an FSM was chosen over a Behavior Tree to reduce overhead and memory allocation on WebGL.

NavMesh over A*: Implementing custom grid-based A* pathfinding in C# would consume significantly more CPU cycles. Unity's compiled C++ NavMesh system is highly optimized and perfectly suited for this prototype.

Brotli Decompression Strategy: To support seamless embedding within Next.js environments without complex custom server headers, the build utilizes pre-decompressed raw assets loaded directly via the modified index.html loader.

Future Expansion Possibilities

  • Squad Coordination Logic
  • Utility AI Scoring (Goal-Oriented)
  • Procedural Level Generation
  • Audio Propagation Systems

From Prototype to Production

Need AI Gameplay Systems for your project?

I build production-ready FSM architectures, adaptive NPC ecosystems, and scalable Unity AI systems — engineered for performance across mobile, WebGL, and desktop platforms.

Interested in high-frame-rate browser deployment? I deliver production-ready WebGL Game Development and customized WebAssembly bundles.