# 2. Gamepad Rumble Service and Patterns Part of [[Haptics and Controller Rumble]]. Previous: [[1. Haptic Design and Platform Support]]. Next: [[3. XR Controller Haptics on Quest]]. > [!warning] Code not compiled > `HapticPattern`, `GamepadRumbleService` and `PlayerRumble` use Input System 1.20 (`Gamepad.SetMotorSpeeds`, `PauseHaptics`, `ResumeHaptics`, `ResetHaptics`, `InputSystem.onDeviceChange`, `PlayerInput.GetDevice<T>()`). Not compiled in Unity. ## 2.1 The naive version and why it breaks ```csharp // Do not ship this. Gamepad.current?.SetMotorSpeeds(0.5f, 0.5f); await Awaitable.WaitForSecondsAsync(0.2f); Gamepad.current?.SetMotorSpeeds(0f, 0f); ``` Problems: 1. **Overlap:** a second hit during the first one's wait gets cut off when the first stops the motors. 2. **Hit-stop:** `WaitForSecondsAsync` uses scaled time; during a 0.05 time-scale freeze from [[4. Hit-Stop Knockback and Feedback]], a 0.2 s rumble lasts 4 s. 3. **Pause:** opening the pause menu mid-rumble leaves the motor spinning. 4. **Quit or scene change:** if the object is destroyed during the wait, the motors never stop. This is the classic "controller keeps buzzing in the menu" bug. 5. **Which pad?** `Gamepad.current` is the last-used gamepad, wrong in local multiplayer. The service below fixes all five. ## 2.2 Install Input System is already set up if you followed [[1. Package Setup and Action Foundations]]. On 6000.5, the package page lists **1.20.1** as released; nothing else is needed for rumble. ## 2.3 HapticPattern.cs (Type Object) ```csharp using UnityEngine; /// <summary> /// One kind of rumble: motor curves over normalized time, a duration and gains. /// Shared by the gamepad service (two motors) and the XR player (one amplitude). /// Not compiled in Unity. /// </summary> [CreateAssetMenu(menuName = "Haptics/Haptic Pattern", fileName = "HapticPattern")] public sealed class HapticPattern : ScriptableObject { [Min(0.01f)] public float duration = 0.12f; [Tooltip("Left, heavy motor. X = normalized time 0..1, Y = speed 0..1.")] public AnimationCurve lowFrequency = AnimationCurve.EaseInOut(0f, 0.6f, 1f, 0f); [Tooltip("Right, sharp motor. X = normalized time 0..1, Y = speed 0..1.")] public AnimationCurve highFrequency = AnimationCurve.EaseInOut(0f, 0.6f, 1f, 0f); [Range(0f, 1f)] public float lowGain = 1f; [Range(0f, 1f)] public float highGain = 1f; [Header("XR (single actuator)")] [Tooltip("XR amplitude = max(low, high) * xrGain.")] [Range(0f, 1f)] public float xrGain = 1f; [Tooltip("0 = device default. Quest 2 support for frequency is unverified; treat as a hint.")] [Min(0f)] public float xrFrequency = 0f; [Tooltip("Ignore Time.timeScale (hit-stop, slow motion). Almost always true.")] public bool unscaledTime = true; public float Low(float normalized) => Mathf.Clamp01(lowFrequency.Evaluate(normalized) * lowGain); public float High(float normalized) => Mathf.Clamp01(highFrequency.Evaluate(normalized) * highGain); public float XRAmplitude(float normalized) => Mathf.Clamp01(Mathf.Max(Low(normalized), High(normalized)) * xrGain); } ``` Explanations: - **Curves over normalized time** let designers shape attack and decay without code. A hit is a curve that starts high and falls quickly; a heartbeat has two bumps. - **Gains** let you reuse one curve shape for light and heavy versions. - **XR mapping** collapses two motors into one amplitude (part 3). One asset, two device families. - Create assets with **Assets > Create > Haptics > Haptic Pattern** and fill them from the table in part 1. ## 2.4 GamepadRumbleService.cs ```csharp using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; /// <summary> /// Plays HapticPatterns on gamepads. Overlapping voices are mixed by maximum per motor, /// scaled by a master intensity, and sent only when the result changes. /// Handles pause, device removal and always resets the motors. Not compiled in Unity. /// </summary> [DefaultExecutionOrder(1000)] // after gameplay has queued this frame's voices public sealed class GamepadRumbleService : MonoBehaviour { public static GamepadRumbleService Instance { get; private set; } [Range(0f, 1f)] [SerializeField] float masterIntensity = 1f; [SerializeField] bool rumbleEnabled = true; [Tooltip("Re-send motor speeds at least this often while active (Android auto-stops after ~10 s).")] [SerializeField, Min(0.1f)] float keepAliveInterval = 1f; [SerializeField, Range(0f, 0.1f)] float changeThreshold = 0.02f; struct Voice { public int handle; public HapticPattern pattern; public float elapsed; public float scale; public bool loop; } sealed class PadState { public readonly List<Voice> voices = new List<Voice>(4); public float sentLow = -1f, sentHigh = -1f; public float sinceSend; } readonly Dictionary<Gamepad, PadState> pads = new Dictionary<Gamepad, PadState>(); readonly List<Gamepad> scratch = new List<Gamepad>(); int nextHandle = 1; bool paused; public float MasterIntensity { get => masterIntensity; set => masterIntensity = Mathf.Clamp01(value); } public bool RumbleEnabled { get => rumbleEnabled; set { rumbleEnabled = value; if (!value) StopAll(); } } void Awake() { if (Instance != null && Instance != this) { Destroy(gameObject); return; } Instance = this; } void OnEnable() => InputSystem.onDeviceChange += OnDeviceChange; void OnDisable() { InputSystem.onDeviceChange -= OnDeviceChange; ResetAllTouched(); } void OnDestroy() { if (Instance == this) Instance = null; } // ---------- public API ---------- /// <summary>Plays a pattern on a gamepad (null = Gamepad.current). Returns a handle for Stop, or 0.</summary> public int Play(HapticPattern pattern, Gamepad pad = null, float scale = 1f, bool loop = false) { if (pattern == null || !rumbleEnabled || masterIntensity <= 0f) return 0; pad ??= Gamepad.current; if (pad == null) return 0; if (!pads.TryGetValue(pad, out var state)) { state = new PadState(); pads.Add(pad, state); } int handle = nextHandle++; state.voices.Add(new Voice { handle = handle, pattern = pattern, scale = Mathf.Max(0f, scale), loop = loop }); return handle; } /// <summary>Plays on every connected gamepad (couch co-op explosions).</summary> public void PlayAll(HapticPattern pattern, float scale = 1f) { foreach (var pad in Gamepad.all) Play(pattern, pad, scale); } public void Stop(int handle) { if (handle == 0) return; foreach (var state in pads.Values) for (int i = state.voices.Count - 1; i >= 0; i--) if (state.voices[i].handle == handle) state.voices.RemoveAt(i); } public void StopAll() { foreach (var state in pads.Values) state.voices.Clear(); ResetAllTouched(); } /// <summary>Call from the pause menu. Motors stop now and resume where they were.</summary> public void SetPaused(bool value) { if (paused == value) return; paused = value; foreach (var pad in pads.Keys) { if (value) pad.PauseHaptics(); else pad.ResumeHaptics(); } } // ---------- mixing ---------- void Update() { if (paused || pads.Count == 0) return; foreach (var pair in pads) { Gamepad pad = pair.Key; PadState state = pair.Value; float low = 0f, high = 0f; for (int i = state.voices.Count - 1; i >= 0; i--) { Voice v = state.voices[i]; v.elapsed += v.pattern.unscaledTime ? Time.unscaledDeltaTime : Time.deltaTime; float n = v.elapsed / v.pattern.duration; if (n >= 1f) { if (!v.loop) { state.voices.RemoveAt(i); continue; } v.elapsed %= v.pattern.duration; n = v.elapsed / v.pattern.duration; } low = Mathf.Max(low, v.pattern.Low(n) * v.scale); high = Mathf.Max(high, v.pattern.High(n) * v.scale); state.voices[i] = v; } low = Mathf.Clamp01(low * masterIntensity); high = Mathf.Clamp01(high * masterIntensity); Send(pad, state, low, high); } } void Send(Gamepad pad, PadState state, float low, float high) { state.sinceSend += Time.unscaledDeltaTime; bool active = low > 0f || high > 0f; bool changed = Mathf.Abs(low - state.sentLow) > changeThreshold || Mathf.Abs(high - state.sentHigh) > changeThreshold; bool fellToZero = !active && (state.sentLow > 0f || state.sentHigh > 0f); bool keepAlive = active && state.sinceSend >= keepAliveInterval; if (!changed && !fellToZero && !keepAlive) return; pad.SetMotorSpeeds(low, high); state.sentLow = low; state.sentHigh = high; state.sinceSend = 0f; } // ---------- lifecycle safety ---------- void OnApplicationPause(bool pause) { // Mobile/Quest style pause; also covers alt-tab on some platforms. if (pause) InputSystem.PauseHaptics(); else if (!paused) InputSystem.ResumeHaptics(); } void OnApplicationFocus(bool focus) { if (!focus) InputSystem.PauseHaptics(); else if (!paused) InputSystem.ResumeHaptics(); } void OnApplicationQuit() => InputSystem.ResetHaptics(); void OnDeviceChange(InputDevice device, InputDeviceChange change) { if (device is not Gamepad pad) return; if (change == InputDeviceChange.Removed || change == InputDeviceChange.Disconnected) pads.Remove(pad); } void ResetAllTouched() { scratch.Clear(); scratch.AddRange(pads.Keys); foreach (var pad in scratch) { pad.ResetHaptics(); var state = pads[pad]; state.sentLow = state.sentHigh = 0f; } } } ``` Walkthrough: - **Voices** are cheap structs per pad. `Play` returns a handle so looping effects (engine idle, low-health) can be stopped. - **Mixing by maximum** (part 1 budget rule). If a heavy hit and a light hit overlap, you feel the heavy one, not a saturated blur. - **Unscaled time by default**: the rumble keeps its real length during hit-stop. That is what you want: the freeze is visual, the hand still feels a 120 ms thump. - **Only send on change.** Each `SetMotorSpeeds` is a device command; sending identical values every frame is wasteful, and some backends are slow. - **Keep-alive**: re-sends active values every second. Required for long effects on Android (auto-stop after about 10 s, Unity 6000.6+) and harmless elsewhere. - **`PauseHaptics` vs `ResetHaptics`**: pause remembers the speeds and `ResumeHaptics` restores them; reset sets them to zero. Pause for menus, reset when leaving. - **`OnDisable` resets**: scene change or service destruction always stops every motor this service touched. - **`DefaultExecutionOrder(1000)`**: voices queued by gameplay this frame are mixed in the same frame. ## 2.5 Wiring pause In your pause flow ([[4. Pause Menu Time Scale and Audio]]), add one line where you set `Time.timeScale = 0`: ```csharp GamepadRumbleService.Instance?.SetPaused(true); // when opening the pause menu GamepadRumbleService.Instance?.SetPaused(false); // when closing it ``` The service's `Update` also skips mixing while paused, so voices freeze and continue afterwards. ## 2.6 PlayerRumble.cs (local multiplayer) `Gamepad.current` is whichever pad was used last. With `PlayerInput` (one per player, [[2. Control Schemes Devices and Consumption Patterns]]), ask the player's own devices: ```csharp using UnityEngine; using UnityEngine.InputSystem; /// <summary> /// Per-player rumble entry point: finds this player's gamepad through PlayerInput. /// Keyboard-and-mouse players simply get no rumble. Not compiled in Unity. /// </summary> [RequireComponent(typeof(PlayerInput))] public sealed class PlayerRumble : MonoBehaviour { PlayerInput playerInput; void Awake() => playerInput = GetComponent<PlayerInput>(); public Gamepad Pad => playerInput != null ? playerInput.GetDevice<Gamepad>() : null; public int Play(HapticPattern pattern, float scale = 1f, bool loop = false) { var pad = Pad; if (pad == null || GamepadRumbleService.Instance == null) return 0; return GamepadRumbleService.Instance.Play(pattern, pad, scale, loop); } public void Stop(int handle) => GamepadRumbleService.Instance?.Stop(handle); } ``` `GetDevice<Gamepad>()` returns the first paired device of that type, or null. In a single-player game without `PlayerInput`, call the service with no pad argument. ## 2.7 Bonus: Xbox trigger rumble and DualShock light bar ```csharp using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.InputSystem.DualShock; using UnityEngine.InputSystem.XInput; /// <summary>Optional device-specific extras. Not compiled in Unity.</summary> public static class GamepadExtras { /// <summary>Trigger motors on Xbox One-style controllers, if the backend exposes them.</summary> public static bool TryTriggerRumble(Gamepad pad, float low, float high, float leftTrigger, float rightTrigger) { if (pad is IXboxOneRumble xbox) { xbox.SetMotorSpeeds(low, high, leftTrigger, rightTrigger); return true; } return false; } /// <summary>Flash the DualShock light bar, e.g. red on low health.</summary> public static bool TrySetLightBar(Gamepad pad, Color color) { if (pad is IDualShockHaptics ds) { ds.SetLightBarColor(color); return true; } return false; } } ``` Whether Windows XInput controllers implement `IXboxOneRumble` outside the console package is **unverified**; the helper returns false when they do not. If you use trigger rumble, the service's own `SetMotorSpeeds` call will overwrite the trigger motors with zero on its next send **(unverified)**, so drive triggers from a separate, short-lived effect and test. ## 2.8 Check - [ ] Two overlapping hit patterns: you feel the stronger one, never a cut-off. - [ ] A hit during hit-stop lasts its real duration. - [ ] Pause mid-rumble: motors stop; resume: they continue. - [ ] Quit to menu mid-rumble: motors stop. - [ ] Two gamepads, two players: each feels only their own hits. ## Sources - Input System 1.20 gamepad haptics: https://docs.unity3d.com/Packages/[email protected]/manual/gamepad-haptics.html - `Gamepad` (`SetMotorSpeeds`, `PauseHaptics`, `ResumeHaptics`, `ResetHaptics`, `current`, `all`): https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.InputSystem.Gamepad.html - `InputSystem` (`PauseHaptics`, `ResumeHaptics`, `ResetHaptics`, `onDeviceChange`): https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.InputSystem.InputSystem.html - `PlayerInput.GetDevice<TDevice>()`: https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.InputSystem.PlayerInput.html - `IXboxOneRumble`: https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.InputSystem.XInput.IXboxOneRumble.html - `IDualShockHaptics`: https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.InputSystem.DualShock.IDualShockHaptics.html - `DefaultExecutionOrder` (6000.5): https://docs.unity.com/en-us/engine/6000.5/script-reference/unityengine/defaultexecutionorder