# 4. FPS Capstone Grunts that Telegraph Part of [[First-Person Shooter Capstone]]. Previous: [[3. FPS Capstone Arsenal Health and Pickups]]. Next: [[5. FPS Capstone Mission HUD and Flow]]. ## 4.1 What makes an enemy fair A grunt with perfect aim and no warning isn't hard, it's annoying. Three rules make the Outpost's grunts fun to fight: 1. **Notice, then act.** On first sight a grunt shouts and pauses for 0.6 s before doing anything. You get a moment to react. 2. **Wind up every shot.** Before each shot the grunt stops, a light on its gun glows (the **tell**), and only 0.5 s later does it fire. Players learn to duck when they see the glow. 3. **No shots through walls.** If you break line of sight during the wind-up, the shot is cancelled and the grunt goes back to chasing. Then **Recover** for 1.2 s after each shot, so even three grunts can't keep you pinned. ## 4.2 The states | State | Enters when | Does | Leaves to | |---|---|---|---| | Patrol | start, or player forgotten | walks between patrol points | Alert on sight | | Alert | first sight | stands, faces you, shouts | Telegraph if in range, else Chase, after 0.6 s | | Chase | out of range or sight lost | paths to you on the NavMesh | Telegraph when in range; Patrol after 4 s unseen | | Telegraph | in range and visible | stands, faces you, tell on | Fire after 0.5 s; Chase if sight lost | | Fire | wind-up complete | one hitscan shot (`Fired` is true for this tick only) | Recover next tick | | Recover | after a shot | stands | Telegraph or Chase after 1.2 s | | Dead | health reaches 0 | nothing | never leaves | Attack range is 18 m and the grunt forgets you after 4 s out of sight. With the defaults, the first shot lands about 1.1 s after a grunt first sees you, and later shots about every 1.7 s. ## 4.3 GruntBrain The decisions are a pure class. It gets a `GruntSenses` struct (can it see the player, how far, is it alive) and a time step, and returns the state. That keeps it testable with no scene at all (part 6), the same split as [[Enemy AI State Machine]]. `Assets/FpsGame/Core/GruntBrain.cs`: **`GruntBrain.cs`** ```csharp using System; public enum GruntState { Patrol, Alert, Chase, Telegraph, Fire, Recover, Dead } /// <summary>What the grunt perceives this tick. Filled by the Grunt component from sensors.</summary> public struct GruntSenses { public bool canSeePlayer; public float distance; public bool alive; } /// <summary> /// A small, readable enemy state machine. Sees you: a short "Alert" beat (it turns and shouts), /// then chases into range. In range with line of sight: it telegraphs (a visible wind-up the player /// can react to), fires once, recovers, and repeats. Loses you: searches for a while, then patrols. /// Pure C#: the component feeds senses and time, and acts on the state and the Fired flag. /// </summary> public sealed class GruntBrain { public float AlertSeconds { get; set; } = 0.6f; public float TelegraphSeconds { get; set; } = 0.5f; public float RecoverSeconds { get; set; } = 1.2f; public float AttackRange { get; set; } = 18f; public float ForgetSeconds { get; set; } = 4f; public GruntState State { get; private set; } = GruntState.Patrol; public float StateTime { get; private set; } public bool Fired { get; private set; } // true for exactly one tick per shot float _sinceSeen = float.PositiveInfinity; public GruntState Tick(GruntSenses s, float dt) { Fired = false; StateTime += dt; if (!s.alive) return Set(GruntState.Dead); if (State == GruntState.Dead) return State; _sinceSeen = s.canSeePlayer ? 0f : _sinceSeen + dt; var inRange = s.canSeePlayer && s.distance <= AttackRange; switch (State) { case GruntState.Patrol: if (s.canSeePlayer) Set(GruntState.Alert); break; case GruntState.Alert: if (StateTime >= AlertSeconds) Set(inRange ? GruntState.Telegraph : GruntState.Chase); break; case GruntState.Chase: if (inRange) Set(GruntState.Telegraph); else if (_sinceSeen > ForgetSeconds) Set(GruntState.Patrol); break; case GruntState.Telegraph: if (!s.canSeePlayer) Set(GruntState.Chase); // lost line of sight: no free hits through walls else if (StateTime >= TelegraphSeconds) { Set(GruntState.Fire); Fired = true; } break; case GruntState.Fire: Set(GruntState.Recover); break; case GruntState.Recover: if (StateTime >= RecoverSeconds) Set(inRange ? GruntState.Telegraph : GruntState.Chase); break; } return State; } GruntState Set(GruntState s) { if (s != State) { State = s; StateTime = 0f; } return State; } } ``` Things to notice: - **`Fired` is an output, not a state you poll.** It is true for exactly one tick. The body shoots when it sees it, so the brain decides *when* and the body decides *how*. - **The dead check comes first.** A grunt killed mid-wind-up can't fire its last shot. - **`StateTime` resets on every change**, so each timer is just "how long have I been in this state". If you want grunts that weigh options instead (retreat when hurt, flank, throw grenades), replace this with a [[Utility AI]] reasoner and keep the same body. ## 4.4 The Grunt body `Assets/FpsGame/Runtime/Grunt.cs`: **`Grunt.cs`** ```csharp using UnityEngine; using UnityEngine.AI; /// <summary> /// An enemy soldier driven by GruntBrain: patrols waypoints, turns and shouts on sight, chases, /// telegraphs each shot with a visible tell, then fires one hitscan shot with some inaccuracy. /// Needs a NavMeshAgent, an FpsHealth (team Enemy) and a Hurtbox on its collider. /// </summary> [RequireComponent(typeof(NavMeshAgent), typeof(FpsHealth))] public sealed class Grunt : MonoBehaviour { [SerializeField] Transform player; [SerializeField] Transform eye; [SerializeField] Transform muzzle; [SerializeField] Transform[] patrolPoints; [SerializeField] GameObject tell; // e.g. a glowing muzzle light, on during Telegraph [SerializeField] AudioSource voice; [SerializeField] AudioClip alertClip, shotClip; [SerializeField] LineRenderer tracer; [SerializeField] AttackDefinition attack; [SerializeField] int damage = 12; [SerializeField] float inaccuracyDegrees = 2.5f; [SerializeField] float viewDistance = 35f; [SerializeField] LayerMask sightMask = Physics.DefaultRaycastLayers; // excludes Ignore Raycast (put pickups and zones there) [SerializeField] float sensorInterval = 0.15f; readonly GruntBrain _brain = new GruntBrain(); NavMeshAgent _agent; FpsHealth _health; GruntSenses _senses; float _nextSense; int _patrolIndex; float _tracerOff; static int s_attackIds = 1_000_000; public GruntState State => _brain.State; void Awake() { _agent = GetComponent<NavMeshAgent>(); _health = GetComponent<FpsHealth>(); _health.Died += OnDied; if (tell != null) tell.SetActive(false); if (tracer != null) tracer.enabled = false; } void Update() { if (Time.time >= _nextSense) { _nextSense = Time.time + sensorInterval; Sense(); } _senses.alive = _health.IsAlive; var before = _brain.State; var state = _brain.Tick(_senses, Time.deltaTime); if (state != before) Enter(state); Act(state); if (_brain.Fired) Shoot(); if (tracer != null && tracer.enabled && Time.time >= _tracerOff) tracer.enabled = false; } void Sense() { _senses.canSeePlayer = false; if (player == null) return; var from = eye != null ? eye.position : transform.position + Vector3.up * 1.6f; var target = player.position + Vector3.up * 1.2f; var to = target - from; _senses.distance = to.magnitude; if (_senses.distance > viewDistance) return; if (Physics.Raycast(from, to / _senses.distance, out var hit, _senses.distance + 0.5f, sightMask, QueryTriggerInteraction.Ignore)) _senses.canSeePlayer = hit.transform == player || hit.transform.IsChildOf(player); } void Enter(GruntState s) { if (tell != null) tell.SetActive(s == GruntState.Telegraph); if (s == GruntState.Alert && voice != null && alertClip != null) voice.PlayOneShot(alertClip); if (s == GruntState.Patrol) NextPatrolPoint(); } void Act(GruntState s) { switch (s) { case GruntState.Patrol: _agent.isStopped = false; if (!_agent.pathPending && _agent.remainingDistance < 0.5f) NextPatrolPoint(); break; case GruntState.Chase: _agent.isStopped = false; if (player != null) _agent.SetDestination(player.position); break; case GruntState.Dead: break; default: // Alert, Telegraph, Fire, Recover: stand and face the player _agent.isStopped = true; FacePlayer(); break; } } void FacePlayer() { if (player == null) return; var flat = player.position - transform.position; flat.y = 0f; if (flat.sqrMagnitude > 0.01f) transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(flat), 540f * Time.deltaTime); } void NextPatrolPoint() { if (patrolPoints == null || patrolPoints.Length == 0) return; _agent.SetDestination(patrolPoints[_patrolIndex].position); _patrolIndex = (_patrolIndex + 1) % patrolPoints.Length; } void Shoot() { if (player == null) return; var origin = muzzle != null ? muzzle.position : transform.position + Vector3.up * 1.4f; var aim = (player.position + Vector3.up * 1.2f - origin).normalized; aim = Quaternion.AngleAxis(Random.Range(-inaccuracyDegrees, inaccuracyDegrees), Vector3.up) * Quaternion.AngleAxis(Random.Range(-inaccuracyDegrees, inaccuracyDegrees), transform.right) * aim; var end = origin + aim * 60f; if (Physics.Raycast(origin, aim, out var hit, 60f, Physics.DefaultRaycastLayers, QueryTriggerInteraction.Collide)) { end = hit.point; HitResolver.TryDamage(hit.collider, hit.point, hit.normal, aim, damage, attack, s_attackIds++, TeamId.Enemy, gameObject); } if (voice != null && shotClip != null) voice.PlayOneShot(shotClip); if (tracer != null) { tracer.SetPosition(0, origin); tracer.SetPosition(1, end); tracer.enabled = true; _tracerOff = Time.time + 0.05f; } } void OnDied(FpsHealth _) { _agent.isStopped = true; _agent.enabled = false; if (tell != null) tell.SetActive(false); foreach (var c in GetComponentsInChildren<Collider>()) c.enabled = false; Destroy(gameObject, 3f); // or ragdoll / pool it; see Object Pooling and Spawners } } ``` How it works: - **Sensing runs every 0.15 s, not every frame.** A raycast per grunt per frame is cheap, but there's no gameplay reason to see faster than about six times a second, and it reads as natural reaction time. - **Sight** is a raycast from the eye to the player's chest that ignores triggers and uses `Physics.DefaultRaycastLayers`, so crates block it but pickup and zone triggers don't. The grunt sees you only if the first thing hit is the player or one of its children. - **On state change**, `Enter` turns the tell on only during Telegraph, plays the alert bark, and picks the next patrol point. - **`Act`** walks the agent in Patrol and Chase, and in every other living state stops it and turns to face you at up to 540°/s. - **`Shoot`** adds a random spread of ±2.5° on each axis, raycasts with `QueryTriggerInteraction.Collide` so it can hit your Hurtbox trigger, and calls `HitResolver.TryDamage` with team **Enemy**. That's the same entry point the player's guns use, so hit-stop, flashes and friendly-fire rules all apply. A `LineRenderer` tracer shows for 0.05 s. - **On death** the agent and colliders are disabled, and the body is destroyed after 3 s. To reuse grunts, return them to a pool instead; see [[Object Pooling and Spawners]]. ## 4.5 Building the grunt prefab ``` Grunt layer Default CapsuleCollider height 1.8, radius 0.35 (blocks sight and movement) NavMeshAgent speed 3.5, angular speed 360, stopping distance 1 FpsHealth team Enemy, max health 60 Grunt AudioSource spatial blend 1 (3D) LineRenderer 2 positions, width 0.02, disabled Hurtbox child: CapsuleCollider (isTrigger), Hurtbox, layer Hurtbox Eye child at y = 1.6 Body mesh capsule plus a box "gun" Muzzle at the gun's tip, inside the capsule's radius Tell small emissive sphere plus a Point Light (range 2, intensity 3), disabled ``` 1. Assign **Player** (the player's root), **Eye**, **Muzzle**, **Tell**, **Voice** (the AudioSource), **Tracer** and an **Attack** definition (a "grunt rifle" `AttackDefinition` with small knockback). 2. Give each grunt two to four **Patrol Points**: empty objects on the NavMesh. 3. Put the yard's six grunts under a `Yard Grunts` parent and the uplink waves under `Uplink Wave A` and `Uplink Wave B`. `MissionDirector` switches these groups on as objectives start (part 5). Keep the **Muzzle inside the grunt's own capsule**. A ray that starts inside a collider doesn't hit that collider, so the grunt can't shoot itself in the face. The friendly-fire check would stop the damage anyway, but the tracer would end at its own chest. ## 4.6 Making the tell readable The tell is the most important thing on the grunt. Make it impossible to miss: - **Colour and light:** a bright orange glow against a grey level. - **Sound:** a short rising "charge" sound on Telegraph. Add it to `Enter` beside the alert bark, for players who are looking elsewhere. - **Pose:** raise the gun to the shoulder during Telegraph if you have animation. Even a 10° rotation of the gun box helps. Play the yard and count: do you ever take damage without knowing why? If so, the tell isn't readable enough yet. Fix that before you touch damage numbers. ## Related - [[Game Programming Patterns (Review)]]: the *State* pattern chapter, including why each state's timer belongs to the state and not to the object. - [[Level Up! (Review)]]: telegraphing and enemy "tells" from its chapters on combat and enemies. - [[Organic Enemy Sensing]] if you want hearing and suspicion meters on top of plain line of sight.