# Frame-Rate-Independent Procedural Springs, Squash-Stretch & Trauma Feel in Unity 6

> Exact dt-invariant second-order critically/under-damped spring dampers, Squirrel Eiserloh T^2 rotational Perlin camera trauma, volume-preserving squash-and-stretch, and TestClock-safe hit-stop.

- **Canonical page:** https://gamecrew.ai/techniques/unity/procedural-springs-game-feel
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Unity 6
- **Category:** gameplay
- **Tags:** `springs`, `game-feel`, `juice`, `camera-shake`, `trauma`, `squash-stretch`, `hitstop`, `animation`, `physics`
- **Verification:** Compile-verified pattern

## When to Use & Field Best Practices

Games feel stiff or fragile when motion uses linear `MoveTowards` or broken frame-dependent `Lerp(a, b, 0.1f)` (which runs at completely different speeds at 30 Hz, 60 Hz, and accelerated PlayMode `TestClock` steps!). Every responsive platformer, brawler, or arcade slice benefits from four composable math primitives:
1. **$\Delta t$-Invariant Exponential Decay & Second-Order Springs**: Parameterize springs by human-intuitive **frequency $f$ (Hz)** and **damping ratio $\zeta$** ($\zeta = 1$: crisp zero-overshoot camera follow; $\zeta \in [0.35, 0.6]$: bouncy UI popups, weapon recoil, landing squash).
2. **Volume-Preserving Squash & Stretch**: When vertical scale compresses to $s_y$ on jump takeoff ($s_y = 1.28$) or landing impact ($s_y = 0.74$), set $s_x = s_z = 1 / \sqrt{s_y}$ on the **visual child transform only** (never scale a `CharacterController` or `Collider`!).
3. **Trauma $T^2$ Rotational Camera Shake** (Eiserloh, GDC 2016): Accumulate scalar `trauma` $\in [0, 1]$ from impacts (`+0.25` to `+0.6`), decay linearly at $\sim 1.4\text{/s}$, and drive **rotational** pitch/yaw/roll offsets proportional to $\text{trauma}^2$ via smooth `Mathf.PerlinNoise` (never `Random.insideUnitSphere` jitter, and never translate camera position through walls).
4. **`TestClock`-Safe Hit-Stop**: Pause or slow a local simulation timer (`_hitStopRemaining -= Time.deltaTime`) on melee/heavy impacts instead of mutating global `Time.timeScale`, because accelerated PlayMode tests (`test-clock.json`) drive `Time.timeScale` themselves!

## Mathematical & Algorithmic Core

### Semi-Implicit Symplectic Spring with Substep Clamp
For angular frequency $\omega = 2\pi f$ and damping ratio $\zeta \ge 0$:
$$a = -\omega^2 (x - x_{\text{target}}) - 2\zeta\omega v$$
Substepping $\Delta t$ into steps $\le \min(\Delta t, \frac{1}{4 f \pi})$ guarantees unconditional stability even during hitches or fast-forwarded `TestClock` ticks while remaining 10 lines of allocation-free code.

### Volume-Preserving Deformation
$$V = s_x \cdot s_y \cdot s_z = 1 \implies s_x = s_z = \frac{1}{\sqrt{\max(0.35, s_y)}}$$

## Engine Implementation

### Reusable Zero-Allocation Feel Primitives (`Assets/Game/Runtime/Core/SpringFeel.cs`)

```csharp
using UnityEngine;

namespace Game.Core
{
    public struct FloatSpring
    {
        public float Value;
        public float Velocity;

        public FloatSpring(float initial)
        {
            Value = initial;
            Velocity = 0f;
        }

        public float Step(float target, float frequencyHz, float dampingRatio, float dt)
        {
            if (dt <= 0f) return Value;
            float omega = 2f * Mathf.PI * Mathf.Max(0.1f, frequencyHz);
            float maxStep = Mathf.Min(0.016f, 0.5f / Mathf.Max(1f, omega));
            float remaining = Mathf.Min(dt, 0.2f);
            while (remaining > 1e-5f)
            {
                float h = Mathf.Min(remaining, maxStep);
                float accel = -omega * omega * (Value - target) - 2f * dampingRatio * omega * Velocity;
                Velocity += accel * h;
                Value += Velocity * h;
                remaining -= h;
            }
            return Value;
        }

        public void Impulse(float velocityDelta) => Velocity += velocityDelta;
    }

    public struct Vector3Spring
    {
        public Vector3 Value;
        public Vector3 Velocity;

        public Vector3Spring(Vector3 initial)
        {
            Value = initial;
            Velocity = Vector3.zero;
        }

        public Vector3 Step(Vector3 target, float frequencyHz, float dampingRatio, float dt)
        {
            if (dt <= 0f) return Value;
            float omega = 2f * Mathf.PI * Mathf.Max(0.1f, frequencyHz);
            float maxStep = Mathf.Min(0.016f, 0.5f / Mathf.Max(1f, omega));
            float remaining = Mathf.Min(dt, 0.2f);
            while (remaining > 1e-5f)
            {
                float h = Mathf.Min(remaining, maxStep);
                Vector3 accel = -omega * omega * (Value - target) - 2f * dampingRatio * omega * Velocity;
                Velocity += accel * h;
                Value += Velocity * h;
                remaining -= h;
            }
            return Value;
        }
    }

    public struct CameraTrauma
    {
        private float _trauma;
        private float _seed;

        public float Trauma => _trauma;

        public void Add(float amount)
        {
            if (_seed == 0f) _seed = 17.3f;
            _trauma = Mathf.Clamp01(_trauma + Mathf.Max(0f, amount));
        }

        public Quaternion SampleRotation(float dt, float time, Vector3 maxAnglesDeg, float frequency = 22f, float recoveryPerSec = 1.45f)
        {
            _trauma = Mathf.Max(0f, _trauma - recoveryPerSec * Mathf.Max(0f, dt));
            float shake = _trauma * _trauma;
            if (shake <= 1e-4f) return Quaternion.identity;

            float t = time * frequency;
            float pitch = (Mathf.PerlinNoise(_seed, t) * 2f - 1f) * maxAnglesDeg.x * shake;
            float yaw   = (Mathf.PerlinNoise(_seed + 31.7f, t) * 2f - 1f) * maxAnglesDeg.y * shake;
            float roll  = (Mathf.PerlinNoise(_seed + 73.1f, t) * 2f - 1f) * maxAnglesDeg.z * shake;
            return Quaternion.Euler(pitch, yaw, roll);
        }
    }

    public static class SquashStretch
    {
        public static Vector3 PreserveVolume(float scaleY, Vector3 baseScale)
        {
            float clampedY = Mathf.Clamp(scaleY, 0.45f, 1.85f);
            float invSqrt = 1f / Mathf.Sqrt(clampedY);
            return new Vector3(baseScale.x * invSqrt, baseScale.y * clampedY, baseScale.z * invSqrt);
        }

        public static float ExpDecay(float current, float target, float decayPerSec, float dt)
        {
            return target + (current - target) * Mathf.Exp(-decayPerSec * Mathf.Max(0f, dt));
        }
    }
}
```

### Applying Squash-Stretch + Trauma Cleanly
- **Character Visual Child**: Keep `Player` root (`CharacterController`) at `Vector3.one`. Put the mesh/model under a `Visual` child transform:
  - On Jump: `_squashSpring.Impulse(+4.5f)` (stretches vertically to ~1.25, narrows XZ to ~0.89).
  - On Land (`!wasGrounded && grounded`): `_squashSpring.Impulse(-Mathf.Clamp(impactSpeed * 0.45f, 2f, 6.5f))`.
  - Each `Update`: `visual.localScale = SquashStretch.PreserveVolume(_squashSpring.Step(1f, 6.5f, 0.45f, Time.deltaTime), _baseScale);`
- **Camera Rig**: Compute clean orbit/follow rotation first, then post-multiply `camera.transform.localRotation = baseRot * _trauma.SampleRotation(Time.deltaTime, Time.time, new Vector3(3.5f, 3.5f, 2.0f));`.

## Browser, Mobile & Software-Renderer Budgets

- **Zero GC Allocations**: `FloatSpring`, `Vector3Spring`, and `CameraTrauma` are value-type `struct`s with zero heap allocations per frame.
- **`TestClock` Determinism**: Never touch `Time.timeScale` for hit-stop (`test-clock.json` runs PlayMode tests at accelerated `Time.timeScale`); instead gate enemy/player simulation ticks on a local `_hitStopTimer > 0f` decremented by `Time.deltaTime`.

## Verification Checklist

1. Write an EditMode unit test proving `FloatSpring.Step` converges to `target` within `0.005f` for both `dt = 1f / 30f` (30 steps) and `dt = 1f / 120f` (120 steps) over 1.0 second.
2. Run `record_test` on jumping/landing and inspect the contact sheet to verify visible takeoff stretch and landing squash without collider snagging.

## Official references

- Squirrel Eiserloh (GDC 2016 — Math for Game Programmers: Juicing Your Cameras With Math)
- Ryan Juckett (Damped Springs)
- Theodoros & Freya Holmér (Frame-Rate Independent Damping)
- Masahiro Sakurai (Hit-Stop / Freeze Frames)
