# Horror Stalker AI, Acoustic Stealth, Flashlight Readability & Liminal Backrooms in Unity 6

> Tension-driven horror stalker AI and readable darkness in Unity 6: patrol/investigate/stalk/chase/search state machine, acoustic noise radius, hiding-spot check logic, volumetric flashlight readability, spatial heartbeat audio, and non-softlocking key-hunt loops.

- **Canonical page:** https://gamecrew.ai/techniques/unity/horror-stalker-ai-backrooms
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Unity 6
- **Category:** ai
- **Tags:** `horror`, `stalker`, `backrooms`, `stealth`, `ai`, `monster`, `flashlight`, `acoustic`, `hiding`, `keys`, `atmosphere`, `vr`, `audio`
- **Verification:** Compile-verified pattern
- **Revision:** 1 (2026-11-30)
- **Demo:** No demo

## When to Use (and When Not To)

Use this architecture for first-person or VR horror games, liminal Backrooms corridors, haunted malls, dark forests, and stealth-escape games where one or more relentless creatures hunt the player by sound and sight while the player searches for keys, fuses, or an exit.

Skip stalker pressure loops in cozy exploration or fast wave-shooter arenas where constant combat clarity matters more than dread and hide-and-seek pacing.

## Mathematical & Algorithmic Core

1. **Dual-Sense Threat Integrator (Sight + Sound)**:
   - **Vision**: Within view range $R_v$ and half-angle $\theta_v$, confirm unobstructed raycast from eye to player head. Multiply detection rate by illumination factor $\ell \in [0.2, 1.0]$ (flashlight ON = `1.0`, crouched in shadow = `0.25`):
     $$\dot{a}_{\text{sight}} = \ell \cdot \left(1 - 0.6\,\frac{d}{R_v}\right) \cdot k_{\text{sight}}$$
   - **Hearing**: Every player action emits a sound impulse with radius $R_s$ (crouch step `2.5 m`, walk `7 m`, sprint/arm-slap `15 m`, thrown distraction `22 m`). If $\|\mathbf{p}_{\text{sound}} - \mathbf{p}_{\text{ai}}\| \le R_s$, record `lastHeardPos` and transition from `Patrol` to `Investigate`.
2. **Tension Pacing Valve (Prevent Impossible Camping)**:
   - Track a **menace timer** $M$. After the stalker stays within `12 m` of a hiding player for more than `10 s` without visual confirmation, switch to `RetreatPatrol` toward a waypoint at least `25 m` away so the player always has windows to move and gather objectives.
3. **Readable Horror Lighting (Never Pitch-Black Monitors)**:
   - Keep ambient fill at a cool/sickly `0.06–0.11` linear intensity with `RenderSettings.fogMode = FogMode.ExponentialSquared` (`density = 0.055–0.095`) so silhouettes read 12–18 m out, and give the monster subtle emissive eyes/teeth highlights + a narrow player flashlight spot (`spotAngle = 48°`, `range = 24 m`, soft inner cone) so every frame has clear figure-ground contrast in WebGL and VR.
4. **VR-Safe Catch & Respawn**: Never yank or lock the VR head camera for jump-scares. Instead, trigger an intense spatial shriek, brief red vignette flash, drop the player back to the current floor/checkpoint with collected key progress preserved (or clearly reset per mode), and put the stalker on a `6 s` grace cooldown at a distant node.

## Engine Implementation

### Acoustic & Sight Horror Stalker (`Assets/Game/Runtime/AI/HorrorStalkerAI.cs`)

```csharp
using System;
using UnityEngine;

namespace Game.AI
{
    public enum StalkerState { Patrol, Investigate, Chase, SearchLastKnown, Retreat }

    public sealed class HorrorStalkerAI : MonoBehaviour
    {
        [Header("References")]
        public Transform Player;
        public Transform[] Waypoints;
        public LayerMask OcclusionMask = ~0;

        [Header("Perception")]
        public float SightRange = 20f;
        public float SightHalfAngleDeg = 52f;
        public float CatchDistance = 1.65f;
        public float AwarenessRiseRate = 1.35f;
        public float AwarenessDecayRate = 0.45f;

        [Header("Movement & Pacing")]
        public float PatrolSpeed = 2.8f;
        public float InvestigateSpeed = 3.9f;
        public float ChaseSpeed = 6.2f;
        public float TurnSpeedDeg = 320f;
        public float MaxCampSeconds = 9f;

        public StalkerState State { get; private set; } = StalkerState.Patrol;
        public float Awareness { get; private set; }
        public float ProximityTension { get; private set; }
        public event Action<StalkerState> StateChanged;
        public event Action PlayerCaught;

        int waypointIdx;
        Vector3 interestPos;
        float stateTimer;
        float closeCampTimer;
        float catchCooldown;
        bool playerHidden;
        bool playerFlashlightOn = true;

        public void SetPlayerStealth(bool hidden, bool flashlightOn)
        {
            playerHidden = hidden;
            playerFlashlightOn = flashlightOn;
        }

        /// <summary>Emit a world-space acoustic event (footstep, door slam, arm-slap, thrown item).</summary>
        public void NotifyNoise(Vector3 worldPos, float hearingRadius)
        {
            if (State == StalkerState.Chase) return;
            float dist = Vector3.Distance(transform.position, worldPos);
            if (dist > hearingRadius) return;
            interestPos = worldPos;
            if (State != StalkerState.Investigate) SetState(StalkerState.Investigate);
            stateTimer = 6.5f;
        }

        public void ResetAfterRespawn(Vector3 farSpawn)
        {
            transform.position = farSpawn;
            Awareness = 0f;
            closeCampTimer = 0f;
            catchCooldown = 6f;
            SetState(StalkerState.Patrol);
        }

        void Update()
        {
            float dt = Mathf.Min(Time.deltaTime, 0.05f);
            if (Player == null) return;
            catchCooldown = Mathf.Max(0f, catchCooldown - dt);

            float distToPlayer = Vector3.Distance(transform.position, Player.position);
            ProximityTension = Mathf.Clamp01(1f - (distToPlayer - 3f) / 22f);

            bool seesPlayer = catchCooldown <= 0f && !playerHidden && CanSeePlayer(distToPlayer);
            if (seesPlayer)
            {
                float lightMul = playerFlashlightOn ? 1f : 0.45f;
                float distMul = Mathf.Lerp(1.2f, 0.45f, distToPlayer / Mathf.Max(1f, SightRange));
                Awareness = Mathf.Clamp01(Awareness + AwarenessRiseRate * lightMul * distMul * dt);
                interestPos = Player.position;
                if (Awareness >= 0.85f && State != StalkerState.Chase) SetState(StalkerState.Chase);
            }
            else
            {
                Awareness = Mathf.Clamp01(Awareness - AwarenessDecayRate * dt);
            }

            // Anti-camping valve: never hover forever outside a player's hiding spot.
            if (State != StalkerState.Chase && distToPlayer < 12f)
            {
                closeCampTimer += dt;
                if (closeCampTimer >= MaxCampSeconds)
                {
                    closeCampTimer = 0f;
                    PickFarthestWaypoint();
                    SetState(StalkerState.Retreat);
                }
            }
            else
            {
                closeCampTimer = Mathf.Max(0f, closeCampTimer - dt * 0.5f);
            }

            StepState(dt, seesPlayer, distToPlayer);
        }

        void StepState(float dt, bool seesPlayer, float distToPlayer)
        {
            switch (State)
            {
                case StalkerState.Patrol:
                    if (MoveToward(CurrentWaypoint(), PatrolSpeed, dt)) AdvanceWaypoint();
                    break;

                case StalkerState.Investigate:
                    stateTimer -= dt;
                    if (MoveToward(interestPos, InvestigateSpeed, dt) || stateTimer <= 0f)
                        SetState(StalkerState.SearchLastKnown);
                    break;

                case StalkerState.Chase:
                    if (seesPlayer)
                    {
                        interestPos = Player.position;
                        stateTimer = 4.0f;
                    }
                    else
                    {
                        stateTimer -= dt;
                        if (stateTimer <= 0f) { SetState(StalkerState.SearchLastKnown); return; }
                    }
                    MoveToward(interestPos, ChaseSpeed, dt);
                    if (catchCooldown <= 0f && distToPlayer <= CatchDistance)
                    {
                        catchCooldown = 6f;
                        PlayerCaught?.Invoke();
                    }
                    break;

                case StalkerState.SearchLastKnown:
                    stateTimer -= dt;
                    transform.Rotate(0f, 90f * dt, 0f);
                    if (stateTimer <= 0f) SetState(StalkerState.Patrol);
                    break;

                case StalkerState.Retreat:
                    if (MoveToward(CurrentWaypoint(), PatrolSpeed * 1.15f, dt)) SetState(StalkerState.Patrol);
                    break;
            }
        }

        bool CanSeePlayer(float dist)
        {
            if (dist > SightRange) return false;
            Vector3 eye = transform.position + Vector3.up * 1.6f;
            Vector3 target = Player.position + Vector3.up * 1.3f;
            Vector3 dir = (target - eye).normalized;
            if (Vector3.Angle(transform.forward, new Vector3(dir.x, 0f, dir.z)) > SightHalfAngleDeg) return false;
            return !Physics.Raycast(eye, dir, dist - 0.35f, OcclusionMask, QueryTriggerInteraction.Ignore);
        }

        bool MoveToward(Vector3 target, float speed, float dt)
        {
            Vector3 flat = new Vector3(target.x - transform.position.x, 0f, target.z - transform.position.z);
            float dist = flat.magnitude;
            if (dist < 0.7f) return true;
            Vector3 dir = flat / dist;
            Quaternion goal = Quaternion.LookRotation(dir, Vector3.up);
            transform.rotation = Quaternion.RotateTowards(transform.rotation, goal, TurnSpeedDeg * dt);
            transform.position += dir * Mathf.Min(speed * dt, dist);
            return false;
        }

        Vector3 CurrentWaypoint() => Waypoints != null && Waypoints.Length > 0 ? Waypoints[waypointIdx % Waypoints.Length].position : transform.position;
        void AdvanceWaypoint() { if (Waypoints != null && Waypoints.Length > 0) waypointIdx = (waypointIdx + 1) % Waypoints.Length; }

        void PickFarthestWaypoint()
        {
            if (Waypoints == null || Waypoints.Length == 0 || Player == null) return;
            float best = -1f;
            for (int i = 0; i < Waypoints.Length; i++)
            {
                float d = (Waypoints[i].position - Player.position).sqrMagnitude;
                if (d > best) { best = d; waypointIdx = i; }
            }
        }

        void SetState(StalkerState next)
        {
            if (State == next) return;
            State = next;
            stateTimer = next == StalkerState.SearchLastKnown ? 3.2f : 5f;
            StateChanged?.Invoke(next);
        }
    }
}
```

## Performance & Platform Traps

- **Backrooms Fluorescent Light Budget**: Never place 40 realtime `PointLight` components down a Backrooms hallway — WebGL 2 URP forward rendering clamps per-object lights and tanks frame rate. Use emissive ceiling panel strips, a single shadow-casting player flashlight (`SpotLight`), and at most 2–3 pooled non-shadow fill lights that leapfrog ahead of the player.
- **Readable Darkness in Headless Captures**: Pure black screenshots look broken. Pair low cool ambient light (`#182026`), subtle distance fog, illuminated exit signs / key glows, and monster emissive eye rims so every room reads clearly even with the flashlight off.
- **No Unwinnable Loops**: Always validate key spawns and exit path reachability in EditMode/PlayMode tests, and respawn the stalker far from the player checkpoint after a catch.

## Verification Checklist

1. Emit a loud noise near the stalker in PlayMode and verify `State` transitions `Patrol -> Investigate`.
2. Place the player in line-of-sight with flashlight on and verify `State` reaches `Chase` and triggers `PlayerCaught` cleanly without freezing input or VR tracking.
3. Capture hallway/arena views with `capture` and confirm silhouettes, keys, and monster eyes remain clearly readable (no crushed-black frames).

## Official references

- Creative Assembly Alien: Isolation Director & Sensory AI (GDC 2015)
- Frictional Games Tension Curve & Horror Pacing Design
- Unity 6 URP Spot Light & Exponential Fog Lighting Guide
