# Active Ragdoll Falls & Bails on a Procedurally Posed Humanoid in Unity 6

> Turn an animated or procedurally posed rigged humanoid into a muscled ragdoll at runtime (no Ragdoll Wizard) for falls and bails, with hinges that hold, no pop or one-step lag at the switch, PD muscle tone that decays, protective reflexes, and a clean hand-back to the animated rig.

- **Canonical page:** https://gamecrew.ai/techniques/unity/active-ragdoll-falls
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Unity 6
- **Category:** physics
- **Tags:** `ragdoll`, `active-ragdoll`, `falls`, `bails`, `configurablejoint`, `characterjoint`, `pd-control`, `rigidbody`, `interpolation`, `protective-reflexes`
- **Verification:** Compile-verified pattern
- **Revision:** 1 (2026-11-13)
- **Demo:** No demo

## When to Use & Field Best Practices

Use this when a character that is normally driven by animation or code (a skater, a runner, a climber) has to fall for real: a bail, a knock-down, a tumble down stairs. The ragdoll is built **at the moment of the fall, from the pose the character is in**, and taken apart when it gets back up. The Ragdoll Wizard's prefab-time setup doesn't fit a procedurally posed rig, and a passive ragdoll looks like a dropped puppet. A short-lived *active* ragdoll looks like a person: it holds its shape, protects its head, and then lets go.

These points come from building one for a real game's bails, and each one cost test runs before it was right:

1. **Elbows and knees are true hinges: use `ConfigurableJoint`, not `CharacterJoint`.** A `CharacterJoint` with small swing limits (a few degrees) does not hold. The forearm rolls round on itself and the elbow folds backward by 50–130 degrees under load. Make a `ConfigurableJoint` with linear motion locked, `angularYMotion` and `angularZMotion` **Locked**, and `angularXMotion` **Limited** about the bend axis. Keep `CharacterJoint` for ball joints (shoulders, hips, neck, spine).
2. **Which sign bends further is not obvious.** `lowAngularXLimit` and `highAngularXLimit` are measured about the joint's `axis` in the bone's own frame, and whether +X bends the elbow further depends on the rig and the axis you pass. Don't guess it: a test bends one hinge toward a target and checks that the angle grew, and the sign is a constant your joint setup reads.
3. **An interpolated rigidbody made in the middle of a frame is drawn one fixed step late.** At the default 50 Hz, a new ragdoll sits still for a frame and then jumps to full speed. In the game that built this, that was a 2 m/s step in the hips and the camera. While the ragdoll is up, run physics at 120 Hz (`Time.fixedDeltaTime = Mathf.Min(was, 1f / 120f)`) and put the old step back when it's taken apart. The joints hold better at that rate too.
4. **Launch each bone at the speed it was drawn moving.** Keep the last two frames of each bone's world position. At the switch, set each new rigidbody's `linearVelocity` to that bone's own velocity, not one velocity for the whole body. Any extra push (the board going out from under the feet, the hit that caused the fall) is spread over about 0.1 s as forces, never one impulse. Together these remove the pop at the switch.
5. **Muscle tone is PD torque toward a target pose, applied to the child and the opposite to its parent.** The equal and opposite torque means the muscles can't spin the whole body in the air (no self-propulsion). The tone holds fully for a moment, then decays to a small rest value, so the body lands, rolls and goes limp.
6. **Protective reflexes are just other targets.** After a short delay (about 60 ms), blend the targets toward a protective shape over about 160 ms: the chin tucked, the spine curled, a shoulder rolled for a roll, or the arms reaching back and down for a breakfall. The motion reads as a person who knows they're falling.
7. **Take the hips out of the animated hierarchy for the duration.** Reparent the hips bone to a world-space root while ragdolled (`SetParent(root, true)`), so the animated body that follows the player can't drag the ragdoll. Afterwards, put back the hips' parent and their local position, rotation and scale.
8. **The character's root follows the ragdoll's hips, taking up their starting offset gradually.** If the root (and the camera on it) snaps to the hips at the switch, the camera jerks. Record the horizontal offset from root to hips when the fall starts, and blend it out over about 0.5 s with a smoothstep.

## Mathematical & Algorithmic Core

- **Per-joint PD acceleration** toward a target rotation $q^\*$ (the parent's rotation times the child's rest rotation relative to it), with $\theta\,\hat{\mathbf{a}}$ the axis-angle of $q^\* q^{-1}$:
  $$\boldsymbol{\alpha} = k_p\,\theta\,\hat{\mathbf{a}} - k_d\,(\boldsymbol{\omega}_{\text{child}} - \boldsymbol{\omega}_{\text{parent}}), \qquad k_d \approx 1.4\sqrt{k_p}$$
  (close to critically damped). Scale $k_p$ by the tone $\tau(t)$ and by each joint's own share: a neck holds more than a wrist.
- **Torque pair:** $\boldsymbol{\tau}_{\text{child}} = \mathrm{clamp}(I\,\boldsymbol{\alpha})$ and $\boldsymbol{\tau}_{\text{parent}} = -\boldsymbol{\tau}_{\text{child}}$, with $I$ a rough inertia (the limb's mass times a small constant). The clamp keeps an error near 180 degrees from exploding.
- **Tone curve:** $\tau(t) = 1$ until $t_h$ (about 0.85 s), then a smoothstep down to $\tau_{\text{rest}}$ (about 0.15) by $t_g$ (about 1.3 s).
- **Bone launch velocity:** $\mathbf{v}_i = (\mathbf{p}_i^{(n)} - \mathbf{p}_i^{(n-1)}) / \Delta t$, from the last two drawn frames.
- **Root take-up:** $\mathbf{r}(t) = \mathbf{h}(t) - \mathbf{o}_0\,(1 - s(k))$, with $s(k) = k^2(3 - 2k)$, $k = \min(1, t / 0.5\,\text{s})$, and $\mathbf{o}_0$ the horizontal offset from root to hips at the switch.

## Engine Implementation

### A hinge that holds (`Assets/Game/Runtime/Player/RagdollJoints.cs`)

```csharp
using UnityEngine;

public static class RagdollJoints
{
    /// <summary>+1 when a positive angular-X limit bends this rig's hinges further; set from a probe test (see below).</summary>
    public const float HingeSign = 1f;

    /// <summary>A knee or elbow: bends about bendAxis (world) from bendNow, between bendLeast and bendMost degrees.</summary>
    public static ConfigurableJoint Hinge(Rigidbody child, Rigidbody parent, Vector3 pivot, Vector3 bendAxis, float bendNow, float bendLeast, float bendMost)
    {
        var j = child.gameObject.AddComponent<ConfigurableJoint>();
        j.connectedBody = parent;
        j.anchor = child.transform.InverseTransformPoint(pivot);
        j.axis = child.transform.InverseTransformDirection(bendAxis);
        Vector3 side = Vector3.Cross(bendAxis, Mathf.Abs(Vector3.Dot(bendAxis, Vector3.up)) < 0.9f ? Vector3.up : Vector3.right).normalized;
        j.secondaryAxis = child.transform.InverseTransformDirection(side);
        j.xMotion = j.yMotion = j.zMotion = ConfigurableJointMotion.Locked;
        // a true hinge: the two other turns locked outright (a CharacterJoint's few degrees of swing let the forearm roll)
        j.angularXMotion = ConfigurableJointMotion.Limited;
        j.angularYMotion = j.angularZMotion = ConfigurableJointMotion.Locked;
        float more = Mathf.Max(0f, bendMost - bendNow), less = Mathf.Max(0f, bendNow - bendLeast);
        float lo = HingeSign > 0f ? -less : -more, hi = HingeSign > 0f ? more : less;
        j.lowAngularXLimit = new SoftJointLimit { limit = Mathf.Clamp(lo, -177f, 0f) };
        j.highAngularXLimit = new SoftJointLimit { limit = Mathf.Clamp(hi, 0f, 177f) };
        j.projectionMode = JointProjectionMode.PositionAndRotation;
        j.projectionDistance = 0.02f;
        j.projectionAngle = 5f;
        return j;
    }
}
```

### The switch: physics rate, hips out, each bone launched as drawn (`Assets/Game/Runtime/Player/ActiveRagdoll.cs`)

```csharp
using System.Collections.Generic;
using UnityEngine;

public class ActiveRagdoll : MonoBehaviour
{
    public Transform hips;
    public Transform[] bones;              // hips first, then each bone that gets a body, parent before child
    public int[] parentOf;                 // index into bones, -1 for the hips
    public float[] mass;

    readonly Vector3[] lastPos = new Vector3[64], prevPos = new Vector3[64];
    readonly List<Rigidbody> bodies = new List<Rigidbody>();
    Quaternion[] restRel;
    float fixedWas, startedAt;
    Transform hipsParentWas, root;
    Vector3 hipsPosWas, hipsScaleWas;
    Quaternion hipsRotWas;

    // keep the last two drawn positions of every bone, so the ragdoll starts at the speed the body was drawn moving
    // (run after whatever poses the body: a later Script Execution Order than the animator or the procedural poser)
    void LateUpdate()
    {
        if (bodies.Count > 0) return;
        for (int i = 0; i < bones.Length; i++) { prevPos[i] = lastPos[i]; lastPos[i] = bones[i].position; }
    }

    /// <summary>Goes limp-but-muscled from the pose it's in; extraPush is a velocity change (m/s) the fall adds, spread over PushTime.</summary>
    public void Fall(Vector3 extraPush)
    {
        // interpolated bodies made mid-frame are drawn a step late: at 50 Hz a still frame, then a jump
        fixedWas = Time.fixedDeltaTime;
        Time.fixedDeltaTime = Mathf.Min(fixedWas, 1f / 120f);
        // the hips out of the animated body into a root of their own, restored when she gets up
        hipsParentWas = hips.parent; hipsPosWas = hips.localPosition; hipsRotWas = hips.localRotation; hipsScaleWas = hips.localScale;
        root = new GameObject("Ragdoll").transform;
        hips.SetParent(root, true);
        float dt = Mathf.Max(Time.deltaTime, 1e-4f);
        restRel = new Quaternion[bones.Length];
        for (int i = 0; i < bones.Length; i++)
        {
            var rb = bones[i].gameObject.AddComponent<Rigidbody>();
            rb.mass = mass[i];
            rb.interpolation = RigidbodyInterpolation.Interpolate;
            rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;
            rb.solverIterations = 12;
            rb.maxDepenetrationVelocity = 2f;
            rb.linearVelocity = (lastPos[i] - prevPos[i]) / dt;   // each bone at its own drawn speed
            bodies.Add(rb);
            if (parentOf[i] >= 0) restRel[i] = Quaternion.Inverse(bones[parentOf[i]].rotation) * bones[i].rotation;
        }
        // (here: a capsule collider per bone sized from its length, RagdollJoints.Hinge for knees and elbows, and a
        // CharacterJoint for each ball joint: shoulders, hips, neck, spine)
        push = extraPush;
        startedAt = Time.time;
    }

    Vector3 push;
    const float PushTime = 0.1f, ToneK = 160f, Hold = 0.85f, Gone = 1.3f, Rest = 0.15f;

    void FixedUpdate()
    {
        if (bodies.Count == 0) return;
        float t = Time.time - startedAt, dt = Time.fixedDeltaTime;
        // the extra push spread over PushTime as an acceleration, never one impulse
        float share = Mathf.Clamp(Mathf.Min(t, PushTime) - Mathf.Max(t - dt, 0f), 0f, dt);
        if (share > 0f) foreach (var rb in bodies) rb.AddForce(push * (share / PushTime / dt), ForceMode.Acceleration);
        float k = ToneK * Tone(t), d = 1.4f * Mathf.Sqrt(Mathf.Max(k, 1f));
        for (int i = 1; i < bodies.Count; i++)
        {
            Rigidbody child = bodies[i], parent = bodies[parentOf[i]];
            Quaternion want = parent.rotation * restRel[i];          // a reflex blends this toward its protective shape
            (want * Quaternion.Inverse(child.rotation)).ToAngleAxis(out float ang, out Vector3 axis);
            if (ang > 180f) ang -= 360f;
            // (at no error the axis is meaningless, and can come back not finite: only the damping acts then)
            bool aimed = ang != 0f && float.IsFinite(axis.x) && float.IsFinite(axis.y) && float.IsFinite(axis.z);
            Vector3 acc = (aimed ? axis * (ang * Mathf.Deg2Rad * k) : Vector3.zero) - (child.angularVelocity - parent.angularVelocity) * d;
            Vector3 torque = Vector3.ClampMagnitude(acc * child.mass * 0.02f, 60f);
            child.AddTorque(torque, ForceMode.Force);
            parent.AddTorque(-torque, ForceMode.Force);              // equal and opposite: no spinning itself in the air
        }
    }

    static float Tone(float t)
    {
        if (t <= Hold) return 1f;
        float k = Mathf.Clamp01((t - Hold) / (Gone - Hold));
        return Mathf.Lerp(1f, Rest, k * k * (3f - 2f * k));
    }

    public void GetUp()
    {
        // (the bones are under the ragdoll's root now, not this object: their joints go first, then their bodies)
        foreach (var b in bones) foreach (var j in b.GetComponents<Joint>()) DestroyImmediate(j);
        foreach (var rb in bodies) if (rb != null) DestroyImmediate(rb);
        bodies.Clear();
        hips.SetParent(hipsParentWas, false);
        hips.localPosition = hipsPosWas; hips.localRotation = hipsRotWas; hips.localScale = hipsScaleWas;
        Destroy(root.gameObject);
        Time.fixedDeltaTime = fixedWas;
    }
}
```

### The player's root follows the hips without a jerk

```csharp
// when the fall starts:   offset0 = hips.position - player.position; offset0.y = 0f; fellAt = Time.time;
Vector3 RootTarget(Vector3 hipsNow, Vector3 offset0, float fellAt)
{
    float k = Mathf.Clamp01((Time.time - fellAt) / 0.5f);
    return hipsNow - offset0 * (1f - k * k * (3f - 2f * k));   // the starting offset taken up over half a second
}
```

## Testing

- **The hinge sign:** a PlayMode test makes one elbow, drives it toward a larger bend for a second, and asserts that the bend between the upper arm and forearm grew. If it shrank, flip `HingeSign`.
- **No fold-back:** a test drops the ragdoll from several poses and seeds, and asserts that no elbow or knee ever bends backward past a few degrees.
- **No pop:** a test records the hips' speed for the frames around the switch and asserts there is no step larger than the speed the body was drawn moving with.
- Tests that render pictures are slow on the studio's machine (software rendering). Keep the pose checks as numbers, and draw a filmstrip only when a person wants to see the motion.

## Official references

- Tan, Liu & Turk, "Stable Proportional-Derivative Controllers" (IEEE CG&A 2011)
- NaturalMotion euphoria (protective-reflex active ragdolls)
- Unity 6 Scripting Reference: ConfigurableJoint, CharacterJoint, Rigidbody.interpolation, Time.fixedDeltaTime
