# 4. Routing Combat Feel Events to Haptics Part of [[Haptics and Controller Rumble]]. Previous: [[3. XR Controller Haptics on Quest]]. Next: [[5. Worked Example Haptics Test Bench and Settings]]. > [!warning] Code not compiled > `HapticEvents`, `HapticFeedbackRouter` and `HapticDamageHook` build on `DamageInfo` and `CombatVictim` from [[Combat Feel and Hit Feedback]]. Not compiled. ## 4.1 Why a bus The combat notes already fan one hit out to knockback, VFX/audio, camera impulse and hit-stop inside `CombatVictim.ApplyDamage` ([[4. Hit-Stop Knockback and Feedback]]). Adding `GamepadRumbleService.Instance.Play(...)` there would work, but: - the victim is usually an **enemy**, while the rumble belongs to the **attacking player's** controller; - the same hit should rumble on a gamepad in the PC build and on the right hand in the Quest build; - designers want to tune "what does a guard feel like" in one place. So gameplay raises a **haptic event** (Observer); a router decides what it feels like and where it goes. ## 4.2 HapticEvents.cs ```csharp using System; using UnityEngine; /// <summary>What happened, from the point of view of a player's hands.</summary> public enum HapticKind { HitDealtLight, HitDealtHeavy, HitTaken, Guard, Knockdown, Death, LowHealthPulse, UIConfirm, Grab, } /// <summary>Which hand(s) an XR event should go to; ignored for gamepads.</summary> public enum HapticHand { Both, Left, Right } /// <summary>One haptic request. Player = the GameObject that owns PlayerRumble or the XR rig; null = default.</summary> public readonly struct HapticEvent { public readonly HapticKind kind; public readonly float strength; // 0..1+, scales the pattern public readonly GameObject player; public readonly HapticHand hand; public HapticEvent(HapticKind kind, float strength = 1f, GameObject player = null, HapticHand hand = HapticHand.Both) { this.kind = kind; this.strength = strength; this.player = player; this.hand = hand; } } /// <summary> /// Static Observer bus. Gameplay calls Raise; routers subscribe. /// Cleared on domain reload so Enter Play Mode Options without reload stays safe. Not compiled in Unity. /// </summary> public static class HapticEvents { public static event Action<HapticEvent> Raised; public static void Raise(in HapticEvent e) => Raised?.Invoke(e); public static void Raise(HapticKind kind, float strength = 1f, GameObject player = null, HapticHand hand = HapticHand.Both) => Raised?.Invoke(new HapticEvent(kind, strength, player, hand)); [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] static void ResetStatics() => Raised = null; } ``` The `SubsystemRegistration` reset matters if you disable domain reload: otherwise the event keeps subscribers from the previous Play session. ## 4.3 HapticFeedbackRouter.cs ```csharp using System; using UnityEngine; /// <summary> /// Maps HapticKinds to HapticPattern assets and sends them to gamepads and/or XR hands. /// One per scene. Not compiled in Unity. /// </summary> public sealed class HapticFeedbackRouter : MonoBehaviour { [Serializable] public struct Entry { public HapticKind kind; public HapticPattern pattern; [Tooltip("Ignore repeats of this kind within this many seconds (unscaled).")] [Min(0f)] public float cooldown; [Tooltip("Per-kind toggle the settings menu can turn off, e.g. LowHealthPulse.")] public bool enabled; } [SerializeField] Entry[] entries = { new Entry { kind = HapticKind.HitDealtLight, cooldown = 0.03f, enabled = true }, new Entry { kind = HapticKind.HitDealtHeavy, cooldown = 0.05f, enabled = true }, new Entry { kind = HapticKind.HitTaken, cooldown = 0.10f, enabled = true }, new Entry { kind = HapticKind.Guard, cooldown = 0.05f, enabled = true }, new Entry { kind = HapticKind.Knockdown, cooldown = 0.50f, enabled = true }, new Entry { kind = HapticKind.Death, cooldown = 1.00f, enabled = true }, new Entry { kind = HapticKind.LowHealthPulse,cooldown = 0.80f, enabled = true }, new Entry { kind = HapticKind.UIConfirm, cooldown = 0.02f, enabled = true }, new Entry { kind = HapticKind.Grab, cooldown = 0.02f, enabled = true }, }; [SerializeField] bool sendToGamepads = true; [SerializeField] bool sendToXR = true; float[] lastPlayed; void Awake() { lastPlayed = new float[Enum.GetValues(typeof(HapticKind)).Length]; for (int i = 0; i < lastPlayed.Length; i++) lastPlayed[i] = float.NegativeInfinity; } void OnEnable() => HapticEvents.Raised += OnRaised; void OnDisable() => HapticEvents.Raised -= OnRaised; public void SetKindEnabled(HapticKind kind, bool value) { for (int i = 0; i < entries.Length; i++) if (entries[i].kind == kind) entries[i].enabled = value; } void OnRaised(HapticEvent e) { if (!TryGetEntry(e.kind, out var entry) || !entry.enabled || entry.pattern == null) return; int k = (int)e.kind; float now = Time.unscaledTime; if (now - lastPlayed[k] < entry.cooldown) return; lastPlayed[k] = now; float scale = Mathf.Clamp(e.strength, 0f, 1.5f); if (sendToGamepads) SendGamepad(entry.pattern, e, scale); if (sendToXR) SendXR(entry.pattern, e, scale); } bool TryGetEntry(HapticKind kind, out Entry entry) { foreach (var x in entries) if (x.kind == kind) { entry = x; return true; } entry = default; return false; } static void SendGamepad(HapticPattern pattern, in HapticEvent e, float scale) { if (e.player != null && e.player.TryGetComponent(out PlayerRumble rumble)) { rumble.Play(pattern, scale); return; } GamepadRumbleService.Instance?.Play(pattern, null, scale); // single player: current pad } static void SendXR(HapticPattern pattern, in HapticEvent e, float scale) { if (e.hand != HapticHand.Right) XRHapticPatternPlayer.For(XRHapticPatternPlayer.Hand.Left)?.Play(pattern, scale); if (e.hand != HapticHand.Left) XRHapticPatternPlayer.For(XRHapticPatternPlayer.Hand.Right)?.Play(pattern, scale); } } ``` Explanations: - **Cooldowns** stop a multi-hit attack (or a shotgun) from stacking a dozen identical voices. The gamepad service would mix them anyway, but the cooldown keeps the feel crisp. - **Strength up to 1.5** lets a heavy hit exceed a pattern's base gain before the final clamp. - **Player routing**: if the event names a player GameObject with `PlayerRumble`, only that pad rumbles. In a Quest build there is one player, so the XR players are static lookups. - **The router depends on both device paths**. In a project with no XR packages, delete `SendXR` and the XR script; in a Quest-only project you can keep the gamepad service (it will simply find no gamepad). ## 4.4 Strength from DamageInfo `DamageInfo` (from [[1. Combat Feel and the Hit Pipeline]]) already carries `amount`, `knockback`, `hitStopDuration`, `source` and `attack`. Derive a 0..1 strength that agrees with the hit-stop and camera impulse the hit already gets: ```csharp using UnityEngine; /// <summary> /// Turns DamageInfo into haptic events for the attacker and the victim. /// Add next to CombatVictim and call from ApplyDamage. Not compiled in Unity. /// </summary> public sealed class HapticDamageHook : MonoBehaviour { [Tooltip("Is this victim a player? Then it also feels HitTaken.")] [SerializeField] bool victimIsPlayer; [Tooltip("Damage at which strength reaches 1.")] [SerializeField, Min(1)] int fullStrengthDamage = 30; [Tooltip("Hit-stop at or above this counts as a heavy hit.")] [SerializeField, Min(0f)] float heavyHitStop = 0.08f; public void OnDamaged(in DamageInfo info, bool killed, bool guarded) { float strength = Mathf.Clamp01((float)info.amount / fullStrengthDamage); strength = Mathf.Max(strength, Mathf.Clamp01(info.hitStopDuration / 0.15f)); GameObject attacker = info.source; if (guarded) { HapticEvents.Raise(HapticKind.Guard, 1f, victimIsPlayer ? gameObject : attacker); return; } bool heavy = info.hitStopDuration >= heavyHitStop; HapticEvents.Raise(heavy ? HapticKind.HitDealtHeavy : HapticKind.HitDealtLight, strength, attacker); if (victimIsPlayer) HapticEvents.Raise(killed ? HapticKind.Death : HapticKind.HitTaken, Mathf.Max(0.5f, strength), gameObject); else if (killed) HapticEvents.Raise(HapticKind.Knockdown, 1f, attacker); } } ``` `info.source` must be the **player root** that owns `PlayerRumble` for local-multiplayer routing; if your attacks set `source` to the weapon, walk up with `GetComponentInParent<PlayerRumble>()` in the router instead. ## 4.5 The one-line hooks Append to `CombatVictim.ApplyDamage` in [[4. Hit-Stop Knockback and Feedback]], after the existing feedback calls (add a `[SerializeField] HapticDamageHook haptics;` field): ```csharp haptics?.OnDamaged(info, killed: _health <= 0, guarded: false); ``` And in the guard path from [[5. I-Frames Dodge and Guard]], where a blocked hit is resolved: ```csharp haptics?.OnDamaged(info, killed: false, guarded: true); ``` UI and VR interaction code raise events directly: ```csharp HapticEvents.Raise(HapticKind.UIConfirm, 1f, null, HapticHand.Right); // poke button pressed with the right hand ``` ## 4.6 Timing with hit-stop and camera shake - The hit sound, `CinemachineImpulseSource` shake ([[4.Impulse Noise and Extensions]]) and rumble all start in `ApplyDamage`, the same frame. Good. - Hit-stop drops `Time.timeScale`; the rumble patterns use **unscaled time** (part 2), so a 120 ms thump stays 120 ms while the picture freezes. This "felt but frozen" moment is a large part of why hit-stop works. - Do not scale rumble *duration* with hit-stop length; scale *strength*. Long rumbles on every heavy hit become noise. ## 4.7 Check - [ ] Light and heavy attacks feel different with eyes closed. - [ ] In two-player local co-op, only the attacker's pad rumbles on a hit they deal. - [ ] Getting hit feels different from hitting. - [ ] A five-hit flurry does not become one continuous buzz. ## Sources - Combat Feel series: [[Combat Feel and Hit Feedback]] (DamageInfo, CombatVictim, HitStopService). - `RuntimeInitializeOnLoadMethod` / `RuntimeInitializeLoadType.SubsystemRegistration` (6000.5): https://docs.unity.com/en-us/engine/6000.5/script-reference/unityengine/runtimeinitializeloadtype/subsystemregistration - Enter Play Mode options / domain reload (6000.5): https://docs.unity.com/en-us/engine/6000.5/manual/scripting/compilation-and-code-reload/code-reloading-editor/configurable-enter-play-mode - Game Programming Patterns, Observer: https://gameprogrammingpatterns.com/observer.html