GameCrew AIEarly access
Sign in
Unity 6aiCompile-verified pattern

Context Steering, Telegraphed Combat & Attack-Token Encounters in Unity 6

Readable enemy and companion AI in Unity 6 using 8-ray context steering maps, FOV + line-of-sight hysteresis, telegraph/active/recovery state machines, and an encounter attack-token director.

  • ai
  • enemy
  • npc
  • steering
  • patrol
  • telegraph
  • combat
  • attack-tokens
  • perception
  • boss

When to Use & Field Best Practices

Great enemy and companion AI is legible, fair, and paced — never omniscient aimbots or rigid navmesh trains that dogpile the player simultaneously:

  1. 8-Ray Context Steering (Andrew Fray, *Game AI Pro 2*): Evaluate an interest[8] array (dot product toward goal or tangent strafe ring) and a danger[8] array (Physics.SphereCast obstacle & hazard probes), mask slots where danger[i] > threshold, and blend the winning direction smoothly. Enemies glide around pillars and flank naturally without getting stuck on corners!
  2. Perception Hysteresis & Last-Known Memory: Require both distance ≤ R_sight, cone f · d ≥ cos(θ/2), and unobstructed Physics.Raycast to acquire aggro, then hold lastSeenPos for 2.5 s after line-of-sight breaks so enemies investigate cover rather than flickering between Patrol and Chase.
  3. Explicit Telegraph → Active → Recovery Windows: Every attack winds up visibly (0.35–0.65 s pullback + emissive rim flash + audio cue) before activating its hitbox, followed by a punishable Recovery window (0.5–0.9 s).
  4. Attack-Token Encounter Director: Limit simultaneous melee lunges/projectiles (maxActiveAttackers = 2) while non-holders orbit on a strafe ring (preferredRadius = 4.5 m).

Mathematical & Algorithmic Core

  • Context Map Slot Evaluation for 8 unit directions u_i = (cos (2π i)/(8), 0, sin (2π i)/(8)): $I_i = max(0, u_i · g), D_i = max_o (1 - fracd_o,iR_probe), S_i = begincases 0 & D_i > 0.65 \\ I_i (1 - D_i) & otherwise endcases$
  • Strafe Ring Interest: Blend radial error (r - r_pref) / r_pref with tangential orbit vector (-g_z, 0, g_x) so waiting enemies circle at readable spacing.

Engine Implementation

Context Steering + Token Director + Telegraphed Enemy (Assets/Game/Runtime/AI/EncounterDirector.cs)

using System.Collections.Generic;
using CCGD;
using UnityEngine;

namespace Game.AI
{
    public sealed class AttackTokenPool
    {
        readonly HashSet<int> holders = new HashSet<int>();
        public int MaxTokens = 2;

        public bool TryAcquire(int actorId)
        {
            if (holders.Contains(actorId)) return true;
            if (holders.Count >= MaxTokens) return false;
            holders.Add(actorId);
            return true;
        }

        public void Release(int actorId) => holders.Remove(actorId);
        public void Clear() => holders.Clear();
    }

    public static class ContextSteering
    {
        static readonly Vector3[] Dirs = BuildDirs();

        static Vector3[] BuildDirs()
        {
            var d = new Vector3[8];
            for (int i = 0; i < 8; i++)
            {
                float a = i * Mathf.PI * 0.25f;
                d[i] = new Vector3(Mathf.Cos(a), 0f, Mathf.Sin(a));
            }
            return d;
        }

        public static Vector3 Solve(Vector3 origin, Vector3 desiredDir, float probeRadius, float probeDist, int obstacleMask)
        {
            Vector3 flatGoal = new Vector3(desiredDir.x, 0f, desiredDir.z);
            if (flatGoal.sqrMagnitude < 1e-5f) return Vector3.zero;
            flatGoal.Normalize();

            Vector3 weighted = Vector3.zero;
            float total = 0f;
            for (int i = 0; i < 8; i++)
            {
                Vector3 u = Dirs[i];
                float interest = Mathf.Max(0.05f, Vector3.Dot(u, flatGoal));
                float danger = 0f;
                if (Physics.SphereCast(origin + Vector3.up * 0.6f, probeRadius, u, out RaycastHit hit, probeDist, obstacleMask, QueryTriggerInteraction.Ignore))
                {
                    danger = Mathf.Clamp01(1f - hit.distance / Mathf.Max(0.05f, probeDist));
                }
                if (danger > 0.7f) continue;
                float score = interest * (1f - danger);
                weighted += u * score;
                total += score;
            }
            return total > 1e-4f ? weighted.normalized : flatGoal;
        }

        public static Vector3 OrbitGoal(Vector3 selfPos, Vector3 targetPos, float preferredRadius, float orbitSign = 1f)
        {
            Vector3 toTarget = targetPos - selfPos;
            toTarget.y = 0f;
            float dist = toTarget.magnitude;
            if (dist < 1e-4f) return Vector3.forward;
            Vector3 radial = toTarget / dist;
            Vector3 tangent = new Vector3(-radial.z * orbitSign, 0f, radial.x * orbitSign);
            float radialWeight = Mathf.Clamp((dist - preferredRadius) / Mathf.Max(0.5f, preferredRadius), -1f, 1f);
            return (radial * radialWeight + tangent * 0.75f).normalized;
        }
    }

    public enum EnemyState { Patrol, Investigate, Strafe, Telegraph, Strike, Recover }

    [RequireComponent(typeof(CharacterController))]
    public sealed class TelegraphedEnemy : MonoBehaviour
    {
        public EnemyState State { get; private set; } = EnemyState.Patrol;
        public Vector3[] Waypoints = System.Array.Empty<Vector3>();
        public int ObstacleMask = ~0;

        CharacterController cc;
        AttackTokenPool pool;
        Transform target;
        Vector3 lastSeenPos;
        int wpIndex;
        float timer, memoryTimer;

        public void Configure(AttackTokenPool tokenPool, Transform playerTarget, Vector3[] patrolPoints)
        {
            cc = GetComponent<CharacterController>();
            pool = tokenPool;
            target = playerTarget;
            Waypoints = patrolPoints ?? System.Array.Empty<Vector3>();
        }

        public void StepAI(float dt)
        {
            if (cc == null) cc = GetComponent<CharacterController>();
            float moveSpeed = Tuning.Value("enemyMoveSpeed", 4.2f);
            float sightRange = Tuning.Value("enemySightRange", 14f);
            float telegraphSec = Tuning.Value("enemyTelegraphSec", 0.45f);
            float recoverSec = Tuning.Value("enemyRecoverSec", 0.65f);

            bool seesPlayer = CanSeeTarget(sightRange, 110f);
            if (seesPlayer)
            {
                lastSeenPos = target.position;
                memoryTimer = 2.5f;
            }
            else if (memoryTimer > 0f)
            {
                memoryTimer -= dt;
            }

            Vector3 moveDir = Vector3.zero;
            int id = GetInstanceID();

            switch (State)
            {
                case EnemyState.Patrol:
                    if (seesPlayer) { State = EnemyState.Strafe; break; }
                    if (Waypoints.Length > 0)
                    {
                        Vector3 wp = Waypoints[wpIndex % Waypoints.Length];
                        if (Vector2.Distance(new Vector2(transform.position.x, transform.position.z), new Vector2(wp.x, wp.z)) < 0.65f)
                            wpIndex = (wpIndex + 1) % Waypoints.Length;
                        moveDir = ContextSteering.Solve(transform.position, wp - transform.position, 0.35f, 2.2f, ObstacleMask) * 0.65f;
                    }
                    break;

                case EnemyState.Strafe:
                    if (!seesPlayer && memoryTimer <= 0f) { pool?.Release(id); State = EnemyState.Patrol; break; }
                    if (!seesPlayer) { State = EnemyState.Investigate; break; }
                    float dist = Vector3.Distance(transform.position, target.position);
                    if (dist < 3.6f && (pool == null || pool.TryAcquire(id)))
                    {
                        State = EnemyState.Telegraph;
                        timer = telegraphSec;
                        GameAudio.Play("telegraph", transform.position);
                        break;
                    }
                    Vector3 orbit = ContextSteering.OrbitGoal(transform.position, target.position, 4.2f, (id & 1) == 0 ? 1f : -1f);
                    moveDir = ContextSteering.Solve(transform.position, orbit, 0.35f, 2.2f, ObstacleMask);
                    break;

                case EnemyState.Investigate:
                    if (seesPlayer) { State = EnemyState.Strafe; break; }
                    if (memoryTimer <= 0f || Vector3.Distance(transform.position, lastSeenPos) < 0.8f) { State = EnemyState.Patrol; break; }
                    moveDir = ContextSteering.Solve(transform.position, lastSeenPos - transform.position, 0.35f, 2.2f, ObstacleMask) * 0.8f;
                    break;

                case EnemyState.Telegraph:
                    Face(target != null ? target.position : lastSeenPos, dt * 10f);
                    timer -= dt;
                    if (timer <= 0f) { State = EnemyState.Strike; timer = 0.22f; }
                    break;

                case EnemyState.Strike:
                    moveDir = transform.forward * 1.65f;
                    timer -= dt;
                    if (timer <= 0f) { pool?.Release(id); State = EnemyState.Recover; timer = recoverSec; }
                    break;

                case EnemyState.Recover:
                    timer -= dt;
                    if (timer <= 0f) State = seesPlayer ? EnemyState.Strafe : EnemyState.Patrol;
                    break;
            }

            if (moveDir.sqrMagnitude > 1e-4f) Face(transform.position + moveDir, dt * 8f);
            Vector3 motion = moveDir * moveSpeed + Vector3.down * 9.81f;
            cc.Move(motion * dt);
        }

        bool CanSeeTarget(float range, float fovDeg)
        {
            if (target == null) return false;
            Vector3 eye = transform.position + Vector3.up * 1.3f;
            Vector3 to = (target.position + Vector3.up * 1.0f) - eye;
            float d = to.magnitude;
            if (d > range || d < 1e-4f) return false;
            if (Vector3.Angle(transform.forward, to / d) > fovDeg * 0.5f) return false;
            return !Physics.Raycast(eye, to / d, d - 0.3f, ObstacleMask, QueryTriggerInteraction.Ignore);
        }

        void Face(Vector3 worldPoint, float rate)
        {
            Vector3 flat = worldPoint - transform.position;
            flat.y = 0f;
            if (flat.sqrMagnitude < 1e-5f) return;
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(flat), Mathf.Clamp01(rate));
        }
    }
}

Performance & Determinism Traps

  • Never raycast 64 directions every frame per enemy: 8 context slots (SphereCast up to 2.2 m) takes < 0.03 ms per actor and handles pillars, walls, and ledges cleanly.
  • Always release attack tokens on death/disable: Call pool.Release(GetInstanceID()) in OnDisable() so defeated enemies never starve the encounter token pool.
  • Keep telegraph durations in Assets/Game/Resources/tuning.json: Declare "enemyMoveSpeed", "enemySightRange", "enemyTelegraphSec", and "enemyRecoverSec" with sane [min, max] bounds so audit_game and live playtest tuning stay synchronized.

Verification Checklist

  1. Write EditMode/PlayMode tests asserting Patrol -> Strafe -> Telegraph -> Strike -> Recover transitions and verifying AttackTokenPool caps simultaneous strikers to MaxTokens.
  2. Run audit_game to verify every Tuning.Value(...) knob and patrol path in level.json is valid.

Official references

  • Andrew Fray (Game AI Pro 2, Ch. 18 — Context Steering: Behavior-Driven Steering at the Macro Scale)
  • Craig Reynolds (GDC 1999 — Steering Behaviors For Autonomous Characters)
  • DOOM 2016 Encounter Token Architecture (GDC 2017)

Playable Unity 6 games made with GameCrew

Launch a real browser build using this engine and inspect its controls or fork its project tree.

Kerbside — Every push, pop and scrape is earned: a grounded skateboarding game where your feet, not a button, do the trick, and a clean landing feels like the real thing.

Kerbside

Every push, pop and scrape is earned: a grounded skateboarding game where your feet, not a button, do the trick, and a clean landing feels like the real thing.

Fjordline — Leap from a granite wall under the midnight sun and carve one unbroken wingsuit line through Norway's most dramatic landscapes, from summit to sea, skimming close enough to touch the rock.

Fjordline

Leap from a granite wall under the midnight sun and carve one unbroken wingsuit line through Norway's most dramatic landscapes, from summit to sea, skimming close enough to touch the rock.

More Unity 6 techniques

lighting

Atmospheric Height Fog, Sun Shafts & Rim-Readable Lighting in Unity 6 URP →

Three-point outdoor/interior URP lighting recipe combining directional sun + warm/cool fill, exponential height/distance fog, ACES/Neutral post-processing, and anti-darkness floors so captures never read black or washed out.

shaders

Cel-Shading, Shadow Ramps & Width-Compensated Outlines in Unity 6 URP →

Two-pass URP stylized cel shader combining main-light shadow-attenuated diffuse ramps, crisp specular/rim accents, and clip-space distance-compensated inverted-hull outlines.

physics

CharacterController Slope Projection & Floor Snap in Unity 6 →

Deterministic Unity 6 CharacterController locomotion with SphereCast ground projection, ramp stickiness, steep-slope slide, and coyote jumps.

optimization

GPU-Instanced Wind Foliage & Interactive Player Bend in Unity 6 URP →

Draw thousands of swaying grass blades, reeds, or wildflowers in 1–4 draw calls using Graphics.RenderMeshInstanced, URP instanced HLSL wind gusts, tip flutter, and player-sphere pushback.

Use verified techniques inside a real game

Describe your game idea for free or connect an MCP assistant to search and contribute techniques.

Learn about collaboration