# 2. Stealth Capstone Player Stealth Kit Part of [[Stealth Game Capstone]]. Prev: [[1. Stealth Capstone Scope Beat Chart and Level Layout]]. Next: [[3. Stealth Capstone Guard Prefab Sensing and NavMesh]]. > [!warning] Code not compiled > None of these scripts has been compiled. They call `StealthTarget` and `NoiseSystem` exactly as written in [[Organic Enemy Sensing]], `InventoryHolder` / `Inventory` / `ItemDefinition` as written in [[Inventory Systems]], and the `IStealthGuard` interface from [[4. Stealth Capstone Guard FSM with Patrol Routes]]. Input uses Input System **1.20.1** (`InputActionReference.action`, `InputAction.IsPressed()`, `WasPressedThisFrame()`, verified in the 1.20 API on 2026-11-21). The player in [[Organic Enemy Sensing]] already has two components: `StealthTarget` (how visible am I?) and `FootstepNoise` (how loud am I?). This part adds the tools a stealth level needs and keeps every one of them a separate component (Component pattern), so you can cut any tool without touching the others. ## 2.1 Player prefab ``` Player (CharacterController or your controller from [[Character Controllers]]) ├── StealthTarget (from Organic Enemy Sensing, with the 2.2 addition) ├── StealthZoneTracker (2.4) ├── StealthCrouch (2.3) ├── SurfaceFootstepNoise (2.5) <- replaces FootstepNoise in this project ├── DistractionThrower (2.6) ├── TakedownAbility (2.7) ├── InventoryHolder (from Inventory Systems: bottles, key card, dossier) ├── CameraTarget (child, for Cinemachine) └── ThrowOrigin (child at right hand height) ``` Input actions (one `Player` action map, see [[Input System]]): `Move`, `Look`, `Crouch` (Button), `Aim` (Button), `Throw` (Button), `Interact` (Button, used for takedowns and pickups). ## 2.2 The one edit to StealthTarget Zones (shadow, foliage) must change how visible the player is, but `StealthTarget.Visibility` has a private setter and is computed from lights every frame. The smallest addition is one property and one multiplier in the existing line: ```csharp // In StealthTarget (Organic Enemy Sensing) - ADD this property: /// Multiplier written by StealthZoneTracker (Stealth Game Capstone). 1 = no zone. public float ZoneMultiplier { get; set; } = 1f; // ...and CHANGE the last line of Update() from // Visibility = LightLevel * (Crouching ? crouchMultiplier : 1f); // to Visibility = LightLevel * (Crouching ? crouchMultiplier : 1f) * ZoneMultiplier; ``` Nothing else in the sensing code changes. `EnemySenses` already multiplies sight gain by `t.Visibility`. > [!note] 6000.5 deprecation in the copied code > `StealthTarget.Start()` calls `FindObjectsByType<Light>(FindObjectsSortMode.None)`. In 6000.5 the overloads that take `FindObjectsSortMode` are **deprecated** (verified on the 6000.5 `Object.FindObjectsByType` page). It still compiles with a warning; the clean replacement is `FindObjectsByType<Light>()`. ## 2.3 Crouch: hold or toggle, with a ceiling check ```csharp using System; using UnityEngine; using UnityEngine.InputSystem; namespace StealthCapstone { /// <summary> /// Crouch with hold or toggle (an accessibility option), resizing a CharacterController /// and writing StealthTarget.Crouching. Will not stand up under a low ceiling. /// Assumes the CharacterController pivot is at the feet. NOT compiled in Unity. /// </summary> [RequireComponent(typeof(StealthTarget))] public sealed class StealthCrouch : MonoBehaviour { public enum Mode { Hold, Toggle } [SerializeField] InputActionReference crouchAction; [SerializeField] Mode mode = Mode.Toggle; [SerializeField] CharacterController controller; // optional [SerializeField, Min(0.5f)] float standHeight = 1.8f; [SerializeField, Min(0.5f)] float crouchHeight = 1.0f; [SerializeField, Range(0.1f, 1f)] float crouchSpeedMultiplier = 0.55f; [SerializeField] LayerMask ceilingMask = ~0; StealthTarget _target; bool _wantCrouch; public bool IsCrouching => _target.Crouching; /// <summary>Your movement controller multiplies its speed by this.</summary> public float SpeedMultiplier => IsCrouching ? crouchSpeedMultiplier : 1f; public event Action<bool> CrouchChanged; public Mode CrouchMode { get => mode; set => mode = value; } void Awake() => _target = GetComponent<StealthTarget>(); void OnEnable() { if (crouchAction) crouchAction.action.Enable(); } void Update() { InputAction a = crouchAction ? crouchAction.action : null; if (a != null) { if (mode == Mode.Hold) _wantCrouch = a.IsPressed(); else if (a.WasPressedThisFrame()) _wantCrouch = !_wantCrouch; } // Stay crouched if the player wants to stand but something is overhead. bool next = _wantCrouch || (IsCrouching && BlockedAbove()); if (next != IsCrouching) Apply(next); } bool BlockedAbove() { if (!controller) return false; float r = controller.radius * 0.95f; Vector3 origin = transform.position + Vector3.up * (crouchHeight - r); float distance = standHeight - crouchHeight; // SphereCast ignores colliders it starts inside, so our own capsule is not hit. return Physics.SphereCast(origin, r, Vector3.up, out _, distance, ceilingMask, QueryTriggerInteraction.Ignore); } void Apply(bool crouch) { _target.Crouching = crouch; if (controller) { float h = crouch ? crouchHeight : standHeight; controller.height = h; controller.center = new Vector3(0f, h * 0.5f, 0f); } CrouchChanged?.Invoke(crouch); } } } ``` **Why toggle is the default:** holding a button for minutes is tiring; [[Accessibility]] recommends offering both. Expose `CrouchMode` in the settings menu ([[Menus, Pause and Settings Flow]]). **Wiring speed:** whatever controller you use, multiply its target speed by `StealthCrouch.SpeedMultiplier`. One line in your controller is better than the crouch script reaching into movement. ## 2.4 Stealth zones: shadow, foliage, surfaces `StealthTarget` estimates light from real `Light` components. That estimate ignores baked GI and emissive surfaces (see its own caveat), so designers need a way to say "this alcove *is* dark" or "this tall grass hides a crouched player". Zones do that, and the same volume type marks noisy surfaces. ```csharp using UnityEngine; namespace StealthCapstone { /// <summary> /// Trigger volume that changes how visible and how loud the player is while inside. /// Shadow: visibility x0.5. Foliage: x0.3 only when crouched. Gravel: noise x1.6. /// NOT compiled in Unity. /// </summary> [RequireComponent(typeof(Collider))] public sealed class StealthZone : MonoBehaviour { public enum Kind { Shadow, Foliage, LitOverride, Surface } [SerializeField] Kind kind = Kind.Shadow; [Tooltip("Multiplies StealthTarget visibility. <1 hides, >1 exposes (neon sign, spotlight).")] [SerializeField, Range(0f, 3f)] float visibilityMultiplier = 0.5f; [Tooltip("Only applies when the player is crouched (tall grass, under a table).")] [SerializeField] bool onlyWhenCrouched; [Tooltip("Multiplies footstep loudness. Gravel 1.6, marble 1.3, carpet 0.6.")] [SerializeField, Range(0f, 3f)] float noiseMultiplier = 1f; [SerializeField] Color gizmoColor = new(0.2f, 0.2f, 0.6f, 0.25f); public Kind ZoneKind => kind; public float NoiseMultiplier => noiseMultiplier; public float VisibilityFor(bool crouching) => onlyWhenCrouched && !crouching ? 1f : visibilityMultiplier; void Reset() => GetComponent<Collider>().isTrigger = true; void OnTriggerEnter(Collider other) { var tracker = other.GetComponentInParent<StealthZoneTracker>(); if (tracker) tracker.Enter(this); } void OnTriggerExit(Collider other) { var tracker = other.GetComponentInParent<StealthZoneTracker>(); if (tracker) tracker.Exit(this); } void OnDisable() { // A zone switched off (lamp turned on, hedge burned) must release the player. StealthZoneTracker.ReleaseEverywhere(this); } void OnDrawGizmos() { if (!TryGetComponent(out BoxCollider box)) return; Gizmos.color = gizmoColor; Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawCube(box.center, box.size); } } } ``` ```csharp using System.Collections.Generic; using UnityEngine; namespace StealthCapstone { /// <summary> /// On the player. Tracks overlapping StealthZones and writes the combined visibility /// multiplier into StealthTarget.ZoneMultiplier every frame. Exposes NoiseMultiplier for /// SurfaceFootstepNoise. NOT compiled in Unity. /// </summary> [RequireComponent(typeof(StealthTarget))] public sealed class StealthZoneTracker : MonoBehaviour { static readonly List<StealthZoneTracker> s_All = new(); readonly List<StealthZone> _zones = new(); StealthTarget _target; public float NoiseMultiplier { get; private set; } = 1f; public bool InAnyHidingZone { get; private set; } void Awake() => _target = GetComponent<StealthTarget>(); void OnEnable() => s_All.Add(this); void OnDisable() { s_All.Remove(this); _zones.Clear(); _target.ZoneMultiplier = 1f; } public void Enter(StealthZone z) { if (!_zones.Contains(z)) _zones.Add(z); } public void Exit(StealthZone z) => _zones.Remove(z); public static void ReleaseEverywhere(StealthZone z) { foreach (var t in s_All) t.Exit(z); } void Update() { float vis = 1f; float noise = 1f; bool hiding = false; bool crouching = _target.Crouching; // Product of visibility multipliers: shadow (0.5) + foliage (0.3) = 0.15. // Noise: the most recently entered Surface zone wins (surfaces should not overlap). for (int i = 0; i < _zones.Count; i++) { StealthZone z = _zones[i]; if (!z) { _zones.RemoveAt(i--); continue; } float v = z.VisibilityFor(crouching); vis *= v; if (v < 0.99f) hiding = true; if (z.ZoneKind == StealthZone.Kind.Surface) noise = z.NoiseMultiplier; } _target.ZoneMultiplier = Mathf.Clamp(vis, 0.05f, 3f); NoiseMultiplier = noise; InAnyHidingZone = hiding; } } } ``` **Design rule (part 1, rule 3):** a Shadow zone is a promise to the player. Put one only where the scene is visibly dark, and paint the floor or add a prop that says "hide here". ## 2.5 Surface-aware footsteps `FootstepNoise` in [[Organic Enemy Sensing]] keeps its loudness fields private. Rather than editing it, this project replaces it with a version that reads the tracker's surface multiplier and raises an event for the HUD's noise ring (part 6). The `NoiseSystem.Emit` call is identical, so guards hear it the same way. ```csharp using System; using UnityEngine; namespace StealthCapstone { /// <summary> /// Replaces FootstepNoise for the capstone: speed-scaled footstep noise, quieter when /// crouched, scaled by the surface zone, emitted through NoiseSystem (Observer). /// NOT compiled in Unity. /// </summary> [RequireComponent(typeof(StealthTarget))] public sealed class SurfaceFootstepNoise : MonoBehaviour { [SerializeField] float walkInterval = 0.5f, runInterval = 0.32f; [SerializeField] float walkLoudness = 6f, runLoudness = 12f, runSpeed = 5f; [SerializeField, Range(0f, 1f)] float crouchFactor = 0.35f; [SerializeField] float minSpeed = 0.5f; [SerializeField] CharacterController controller; // optional, preferred for speed [SerializeField] AudioSource footstepSource; // optional [SerializeField] AudioClip[] footstepClips; StealthTarget _stealth; StealthZoneTracker _zones; Vector3 _lastPos; float _timer; /// <summary>World position and loudness (metres) of each emitted step.</summary> public event Action<Vector3, float> Stepped; void Awake() { _stealth = GetComponent<StealthTarget>(); _zones = GetComponent<StealthZoneTracker>(); _lastPos = transform.position; } void Update() { float speed = HorizontalSpeed(); if (speed < minSpeed) { _timer = 0f; return; } _timer -= Time.deltaTime; if (_timer > 0f) return; float t = Mathf.Clamp01(speed / runSpeed); _timer = Mathf.Lerp(walkInterval, runInterval, t); float loud = Mathf.Lerp(walkLoudness, runLoudness, t); if (_stealth.Crouching) loud *= crouchFactor; if (_zones) loud *= _zones.NoiseMultiplier; NoiseSystem.Emit(transform.position, loud, gameObject); Stepped?.Invoke(transform.position, loud); PlayClip(t); } float HorizontalSpeed() { Vector3 v; if (controller) v = controller.velocity; else { v = (transform.position - _lastPos) / Mathf.Max(Time.deltaTime, 1e-5f); _lastPos = transform.position; } v.y = 0f; return v.magnitude; } void PlayClip(float runAmount) { if (!footstepSource || footstepClips == null || footstepClips.Length == 0) return; var clip = footstepClips[UnityEngine.Random.Range(0, footstepClips.Length)]; footstepSource.pitch = UnityEngine.Random.Range(0.95f, 1.05f); footstepSource.PlayOneShot(clip, Mathf.Lerp(0.35f, 1f, runAmount) * (_stealth.Crouching ? 0.5f : 1f)); } } } ``` > [!tip] Audible = heard > Keep the *audio* volume proportional to the *gameplay* loudness. If the player can't hear their own steps on gravel, they can't learn that gravel is loud. The richer audio setup is in [[Interactable Audio]] and [[Spatial Audio and Reverb Zones]]. ## 2.6 Distraction throws A thrown bottle is a noise at a place *you* choose. `EnemySenses.OnNoise` only sets `Target` when the noise source has a `StealthTarget`, so a bottle moves the guard's `LastKnownPosition` without revealing the player - exactly what a distraction should do. Noise alone caps awareness at 0.95, so a bottle makes guards **investigate**, never chase. ```csharp using UnityEngine; namespace StealthCapstone { /// <summary> /// Thrown object that emits a noise on its first hard impact (and quieter ones after). /// Needs a Rigidbody and a non-trigger Collider. NOT compiled in Unity. /// </summary> [RequireComponent(typeof(Rigidbody))] public sealed class ThrowableDistraction : MonoBehaviour { [SerializeField] float loudness = 14f; // metres, open air [SerializeField] float minImpactSpeed = 2f; [SerializeField] float referenceSpeed = 10f; // speed that gives full loudness [SerializeField] float bounceCooldown = 0.25f; [SerializeField] int maxNoises = 3; [SerializeField] float lifetime = 12f; [SerializeField] bool shatterOnFirstImpact = true; [SerializeField] GameObject shatterPrefab; // optional shards + sound int _noises; float _nextAllowed; void Start() => Destroy(gameObject, lifetime); void OnCollisionEnter(Collision c) { if (_noises >= maxNoises || Time.time < _nextAllowed) return; float speed = c.relativeVelocity.magnitude; if (speed < minImpactSpeed) return; _nextAllowed = Time.time + bounceCooldown; float strength = Mathf.Clamp01(speed / referenceSpeed); float loud = loudness * Mathf.Lerp(0.4f, 1f, strength) * (_noises == 0 ? 1f : 0.5f); Vector3 p = c.GetContact(0).point; NoiseSystem.Emit(p, loud, gameObject); _noises++; if (shatterOnFirstImpact) { if (shatterPrefab) Instantiate(shatterPrefab, p, Quaternion.identity); Destroy(gameObject); } } } } ``` ```csharp using System; using System.Collections.Generic; using Inventories; using UnityEngine; using UnityEngine.InputSystem; namespace StealthCapstone { /// <summary> /// Hold Aim to show a ballistic arc, press Throw to spend one throwable item from the /// player's Inventory and launch its prefab. NOT compiled in Unity. /// </summary> public sealed class DistractionThrower : MonoBehaviour { [SerializeField] InputActionReference aimAction; [SerializeField] InputActionReference throwAction; [SerializeField] InventoryHolder holder; [SerializeField] ItemDefinition throwableItem; // e.g. "bottle", maxStack 3 [SerializeField] Rigidbody throwablePrefab; // has ThrowableDistraction [SerializeField] Transform throwOrigin; [SerializeField] Transform aimCamera; // usually Camera.main.transform [SerializeField] float throwSpeed = 12f; [SerializeField, Range(0f, 60f)] float upAngle = 20f; [SerializeField] LineRenderer arc; // optional preview [SerializeField, Range(8, 60)] int arcPoints = 30; [SerializeField] float arcTimeStep = 0.05f; [SerializeField] LayerMask arcCollision = ~0; readonly List<Vector3> _points = new(); public event Action<Vector3> Thrown; // stats / telemetry void OnEnable() { if (aimAction) aimAction.action.Enable(); if (throwAction) throwAction.action.Enable(); } void Update() { bool aiming = aimAction && aimAction.action.IsPressed() && HasAmmo(); if (arc) arc.enabled = aiming; if (!aiming) return; Vector3 v0 = LaunchVelocity(); if (arc) DrawArc(throwOrigin.position, v0); if (throwAction && throwAction.action.WasPressedThisFrame()) Throw(v0); } bool HasAmmo() => holder && throwableItem && holder.Inventory.Has(throwableItem); Vector3 LaunchVelocity() { Vector3 fwd = aimCamera ? aimCamera.forward : transform.forward; fwd.y = 0f; if (fwd.sqrMagnitude < 1e-4f) fwd = transform.forward; fwd.Normalize(); Vector3 right = Vector3.Cross(Vector3.up, fwd); Vector3 dir = Quaternion.AngleAxis(-upAngle, right) * fwd; return dir * throwSpeed; } void Throw(Vector3 v0) { if (holder.Inventory.Remove(throwableItem, 1) != 1) return; Rigidbody rb = Instantiate(throwablePrefab, throwOrigin.position, Quaternion.identity); rb.linearVelocity = v0; rb.angularVelocity = UnityEngine.Random.insideUnitSphere * 6f; Thrown?.Invoke(throwOrigin.position); } void DrawArc(Vector3 p0, Vector3 v0) { _points.Clear(); Vector3 g = Physics.gravity; Vector3 prev = p0; _points.Add(prev); for (int i = 1; i < arcPoints; i++) { float t = i * arcTimeStep; Vector3 p = p0 + v0 * t + 0.5f * t * t * g; if (Physics.Linecast(prev, p, out RaycastHit hit, arcCollision, QueryTriggerInteraction.Ignore)) { _points.Add(hit.point); break; } _points.Add(p); prev = p; } arc.positionCount = _points.Count; for (int i = 0; i < _points.Count; i++) arc.SetPosition(i, _points[i]); } } } ``` **Why spend an Inventory item:** bottles become a resource the level hands out on side routes (part 1's reward column), and [[Inventory Systems]] already handles stacking, pickups (`WorldPickup`) and the UI. Make the bottle `ItemDefinition` stackable (`maxStack = 3`), not a quest item. ## 2.7 Takedown from behind A takedown is allowed only when the guard is **not fully alerted** and the player is **behind** them. The guard decides (it owns its own state); the player script only asks. ```csharp using System; using UnityEngine; using UnityEngine.InputSystem; namespace StealthCapstone { /// <summary> /// Press Interact near a guard's back to knock them out. Uses a non-allocating overlap. /// The guard (IStealthGuard: GuardBrain in part 4 or BehaviorGuard in part 5) decides whether the takedown is legal. /// NOT compiled in Unity. /// </summary> public sealed class TakedownAbility : MonoBehaviour { [SerializeField] InputActionReference interactAction; [SerializeField] float reach = 1.4f; [SerializeField] float forwardOffset = 0.7f; [SerializeField] LayerMask guardMask; [SerializeField] float takedownNoise = 3f; // a scuffle is quiet, not silent [SerializeField] float cooldown = 1f; readonly Collider[] _hits = new Collider[8]; float _next; public event Action<IStealthGuard> TakedownPerformed; /// <summary>The guard currently in takedown position, for a prompt (or null).</summary> public IStealthGuard Candidate { get; private set; } void OnEnable() { if (interactAction) interactAction.action.Enable(); } void Update() { Candidate = FindCandidate(); if (Candidate == null || Time.time < _next) return; if (interactAction && interactAction.action.WasPressedThisFrame()) { _next = Time.time + cooldown; Candidate.KnockOut(); NoiseSystem.Emit(transform.position, takedownNoise, gameObject); TakedownPerformed?.Invoke(Candidate); } } IStealthGuard FindCandidate() { Vector3 centre = transform.position + transform.forward * forwardOffset + Vector3.up; int n = Physics.OverlapSphereNonAlloc(centre, reach, _hits, guardMask, QueryTriggerInteraction.Ignore); IStealthGuard best = null; float bestDist = float.MaxValue; for (int i = 0; i < n; i++) { var g = _hits[i].GetComponentInParent<IStealthGuard>(); if (g == null || !g.CanBeTakenDownFrom(transform.position)) continue; float d = (g.transform.position - transform.position).sqrMagnitude; if (d < bestDist) { bestDist = d; best = g; } } return best; } void OnDrawGizmosSelected() { Gizmos.color = Color.magenta; Gizmos.DrawWireSphere(transform.position + transform.forward * forwardOffset + Vector3.up, reach); } } } ``` Show `Candidate` with a prompt ("[E] Takedown") using [[Context-Sensitive Prompts and Onboarding]]. Takedowns cost the Ghost rating (part 6), which is how the design keeps them a choice and not the default answer. ## 2.8 Test checklist 1. Stand in a lamp pool, then a Shadow zone: watch `StealthTarget.Visibility` drop in the Inspector (Debug mode). 2. Crouch under a 1.2 m ceiling and release crouch: you stay crouched until you leave. 3. Walk on gravel next to a guard: the guard turns to investigate; on carpet it does not. 4. Throw a bottle behind a guard: it goes to the shatter point (Investigate, part 4) and never chases. 5. Approach from the front and press Interact: nothing happens. From behind: knockout. ## Sources - Input System for 6000.5 (1.20.1): https://docs.unity3d.com/6000.5/Documentation/Manual/com.unity.inputsystem.html - `InputAction` API (1.20): https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.InputSystem.InputAction.html - `InputActionReference` API (1.20): https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.InputSystem.InputActionReference.html - `Physics.OverlapSphereNonAlloc` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Physics.OverlapSphereNonAlloc.html - `CharacterController.velocity` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/CharacterController-velocity.html - `Rigidbody.linearVelocity` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Rigidbody-linearVelocity.html - `Object.FindObjectsByType` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Object.FindObjectsByType.html