# 5. Ragdoll Setup and Blending
Part of [[Procedural Animation and IK]]. Previous: [[4. Procedural Stepping and Secondary Motion]]. Next: [[6. Worked Example Grounded Guard with Knockdown]].
> [!warning] Code not compiled
> `RagdollController` uses `Rigidbody.isKinematic`, `linearVelocity`, `AddForceAtPosition`, `Animator.Play`, `Animator.Update`, `Animator.GetBoneTransform` and `GetCurrentAnimatorStateInfo` from the 6000.5 Scripting Reference. Not compiled or play-tested.
Switching a character to ragdoll is easy. Getting it **back** to animation without a visible pop is the real work: the ragdoll lies wherever physics left it, but the get-up clip starts with the character standing on its root. This part handles both directions.
## 5.1 Build the ragdoll with the wizard
The 6000.5 manual's procedure:
1. Select the character FBX; in **Import Settings > Model**, turn **Generate Colliders** off if it is on.
2. Drag an instance into the scene.
3. **GameObject > 3D Object > Ragdoll...** opens the Ragdoll Wizard.
4. Drag bones from the Hierarchy into each slot: pelvis, hips/knees/feet (thigh, shin, foot), arms/elbows (upper arm, forearm), middle spine and head. *(The slot names are from the wizard window; the manual page does not list them, so match what your editor shows.)*
5. Set a **Total Mass** (70-80 kg for an adult) and click **Create**. The wizard adds a Rigidbody, a collider and (except on the pelvis) a **Character Joint** to each bone.
6. Apply the changes to your prefab.
The manual names the Character Joint axes: **Twist** twists the limb, **Swing 1** is the largest swing axis, **Swing 2** the smaller one. If an elbow bends backwards, that joint's Twist limits are the ones to fix ([[4. Joints]]).
## 5.2 Layers and collision
1. Put every ragdoll bone (the GameObjects with Rigidbodies) on a **`Ragdoll`** layer. Leave the root with the CharacterController on `Character`.
2. **Project Settings > Physics > Layer Collision Matrix:** untick **Ragdoll x Character**. Otherwise the CharacterController capsule overlaps the limbs and the first frame of ragdoll launches the body into the air ([[3. Layers Matrix and Queries]]).
3. Keep **Ragdoll x Ragdoll** ticked only if you want limbs to collide with each other; the Character Joints already ignore collisions between connected bodies by default (*Enable Collision* off on the joint).
4. Set each ragdoll Rigidbody's **Interpolate** to **Interpolate** and **Collision Detection** to **Continuous Speculative** while ragdolling, so fast falls do not tunnel through thin floors ([[5. Forces FixedUpdate and Motion Modes]]).
## 5.3 Get-up clips
You need two clips: **get up from lying on the back** and **from lying on the front**. Mixamo has both. Import them as Humanoid, add them to the Animator Controller as states named `GetUpFromBack` and `GetUpFromFront` with **no incoming transitions** (the script plays them directly) and an exit transition back to locomotion on **Exit Time 1**.
Open each clip and look at **frame 0**: which way does the character's root forward point relative to its head? Most Mixamo get-up clips lying on the back have the head **behind** the root (the character faces toward its feet). Record this for each clip; the script has a checkbox for it.
## 5.4 RagdollController.cs
```csharp
using System;
using UnityEngine;
/// <summary>
/// Animated <-> ragdoll switching for a Humanoid with a pose-blended get-up.
/// Put it on the root that has the Animator (and the CharacterController, if any).
/// States: Animated -> Ragdoll (Knockdown) -> GettingUp (blend from ragdoll snapshot) -> Animated.
/// Not compiled in an editor.
/// </summary>
[RequireComponent(typeof(Animator))]
public sealed class RagdollController : MonoBehaviour
{
public enum State { Animated, Ragdoll, GettingUp }
[Header("References")]
[SerializeField] CharacterController characterController;
[Tooltip("Movers, AI, foot IK, NavMeshAgent... anything that must stop while ragdolling.")]
[SerializeField] Behaviour[] disableWhileRagdoll = Array.Empty<Behaviour>();
[Header("Ragdoll")]
[Tooltip("Keep ragdoll colliders enabled while animated (as kinematic hurtboxes).")]
[SerializeField] bool collidersWhileAnimated = false;
[SerializeField] float minRagdollSeconds = 1.2f;
[SerializeField] float settleSpeed = 0.2f;
[SerializeField] float settleSeconds = 0.5f;
[SerializeField] float maxRagdollSeconds = 6f;
[SerializeField] LayerMask groundMask = 1;
[Header("Get up")]
[SerializeField] string getUpFromBackState = "GetUpFromBack";
[SerializeField] string getUpFromFrontState = "GetUpFromFront";
[SerializeField] int animatorLayer = 0;
[Tooltip("Hips local axis that points out of the belly. Mixamo hips: usually +Z.")]
[SerializeField] Vector3 hipsBellyAxis = Vector3.forward;
[Tooltip("At frame 0 of the back clip, does the root face toward the feet?")]
[SerializeField] bool backClipFacesFeet = true;
[Tooltip("At frame 0 of the front clip, does the root face toward the feet?")]
[SerializeField] bool frontClipFacesFeet = false;
[SerializeField] float blendSeconds = 0.5f;
[SerializeField] float getUpTimeout = 4f;
Animator animator;
Transform hips, head;
Rigidbody hipsBody;
Rigidbody[] bodies;
Collider[] colliders;
Transform[] bones;
Quaternion[] snapshotLocal;
Vector3 snapshotHipsPos;
Quaternion snapshotHipsRot;
string getUpState;
State state = State.Animated;
float stateTime, stillTime;
public State Current => state;
public event Action<State> StateChanged;
void Awake()
{
animator = GetComponent<Animator>();
hips = animator.GetBoneTransform(HumanBodyBones.Hips);
head = animator.GetBoneTransform(HumanBodyBones.Head);
bodies = hips.GetComponentsInChildren<Rigidbody>(true);
colliders = hips.GetComponentsInChildren<Collider>(true);
bones = hips.GetComponentsInChildren<Transform>(true); // bones[0] == hips
snapshotLocal = new Quaternion[bones.Length];
hipsBody = hips.GetComponent<Rigidbody>();
SetPhysics(false);
}
// ---------- Public API ----------
/// <summary>Switch to ragdoll and push the body part nearest to the hit point.</summary>
public void Knockdown(Vector3 impulse, Vector3 hitPoint, Rigidbody hitBody = null)
{
if (state == State.Ragdoll) { Push(impulse, hitPoint, hitBody); return; }
Vector3 inherited = characterController != null ? characterController.velocity : Vector3.zero;
foreach (var b in disableWhileRagdoll) if (b != null) b.enabled = false;
if (characterController != null) characterController.enabled = false;
animator.enabled = false; // the last animated pose stays on the bones
SetPhysics(true);
foreach (var rb in bodies) rb.linearVelocity = inherited; // keep running momentum
Push(impulse, hitPoint, hitBody);
Enter(State.Ragdoll);
}
// ---------- State machine ----------
void Update()
{
stateTime += Time.deltaTime;
if (state != State.Ragdoll) return;
float speed = hipsBody != null ? hipsBody.linearVelocity.magnitude : 0f;
stillTime = speed < settleSpeed ? stillTime + Time.deltaTime : 0f;
bool settled = stateTime >= minRagdollSeconds && stillTime >= settleSeconds;
if (settled || stateTime >= maxRagdollSeconds) BeginGetUp();
}
void LateUpdate()
{
if (state != State.GettingUp) return;
// The Animator has written this frame's get-up pose. Blend from the ragdoll
// snapshot toward it, so the first frames match where the body actually lay.
float t = Mathf.Clamp01(stateTime / blendSeconds);
float fromSnapshot = 1f - t * t * (3f - 2f * t); // smoothstep, 1 -> 0
if (fromSnapshot > 0f)
{
hips.SetPositionAndRotation(
Vector3.Lerp(hips.position, snapshotHipsPos, fromSnapshot),
Quaternion.Slerp(hips.rotation, snapshotHipsRot, fromSnapshot));
for (int i = 1; i < bones.Length; i++)
bones[i].localRotation = Quaternion.Slerp(bones[i].localRotation, snapshotLocal[i], fromSnapshot);
}
bool clipDone = t >= 1f && !animator.GetCurrentAnimatorStateInfo(animatorLayer).IsName(getUpState);
if (clipDone || stateTime >= getUpTimeout) FinishGetUp();
}
void BeginGetUp()
{
bool faceUp = Vector3.Dot(hips.TransformDirection(hipsBellyAxis), Vector3.up) > 0f;
getUpState = faceUp ? getUpFromBackState : getUpFromFrontState;
bool facesFeet = faceUp ? backClipFacesFeet : frontClipFacesFeet;
// 1. Remember where the hips are, then move the root under them.
Vector3 hipsPos = hips.position;
Quaternion hipsRot = hips.rotation;
Vector3 rootPos = hipsPos;
if (Physics.Raycast(hipsPos + Vector3.up * 0.5f, Vector3.down, out RaycastHit hit, 3f,
groundMask, QueryTriggerInteraction.Ignore))
rootPos.y = hit.point.y;
else
rootPos.y = transform.position.y;
Vector3 headToHips = Vector3.ProjectOnPlane(hipsPos - head.position, Vector3.up);
if (headToHips.sqrMagnitude < 0.0001f) headToHips = transform.forward;
Vector3 forward = facesFeet ? headToHips.normalized : -headToHips.normalized;
transform.SetPositionAndRotation(rootPos, Quaternion.LookRotation(forward, Vector3.up));
hips.SetPositionAndRotation(hipsPos, hipsRot); // moving the root moved the hips; put them back
// 2. Snapshot the ragdoll pose.
snapshotHipsPos = hips.position;
snapshotHipsRot = hips.rotation;
for (int i = 0; i < bones.Length; i++) snapshotLocal[i] = bones[i].localRotation;
// 3. Physics off, animation on, start the get-up clip at frame 0 and evaluate it now.
SetPhysics(false);
animator.enabled = true;
animator.Play(getUpState, animatorLayer, 0f);
animator.Update(0f);
Enter(State.GettingUp);
}
void FinishGetUp()
{
if (characterController != null) characterController.enabled = true;
foreach (var b in disableWhileRagdoll) if (b != null) b.enabled = true;
Enter(State.Animated);
}
// ---------- Helpers ----------
void Push(Vector3 impulse, Vector3 point, Rigidbody body)
{
if (body == null) body = Closest(point);
if (body != null) body.AddForceAtPosition(impulse, point, ForceMode.Impulse);
}
Rigidbody Closest(Vector3 point)
{
Rigidbody best = null;
float bestSqr = float.MaxValue;
foreach (var rb in bodies)
{
float d = (rb.worldCenterOfMass - point).sqrMagnitude;
if (d < bestSqr) { bestSqr = d; best = rb; }
}
return best;
}
void SetPhysics(bool ragdoll)
{
foreach (var rb in bodies)
{
rb.isKinematic = !ragdoll;
rb.interpolation = ragdoll ? RigidbodyInterpolation.Interpolate : RigidbodyInterpolation.None;
rb.collisionDetectionMode = ragdoll ? CollisionDetectionMode.ContinuousSpeculative
: CollisionDetectionMode.Discrete;
}
foreach (var c in colliders) c.enabled = ragdoll || collidersWhileAnimated;
}
void Enter(State next)
{
state = next;
stateTime = 0f;
stillTime = 0f;
StateChanged?.Invoke(next);
}
}
```
## 5.5 Walkthrough of the tricky parts
**Kinematic until needed.** While animated, every ragdoll Rigidbody is kinematic, so the Animator owns the bones and physics just follows. With `collidersWhileAnimated` on, those colliders double as hit-detection volumes (a kinematic body is moved by its transform and still reports trigger/collision queries). If you already use separate hurtboxes from [[3. Hitboxes and Hurtboxes]], leave it off.
**Inherited velocity.** A running character that is knocked down should keep sliding forward. Copying the CharacterController's velocity to every body before the impulse does that.
**Settle detection.** Waiting for the hips' speed to stay below `settleSpeed` for `settleSeconds` avoids getting up while still rolling. `maxRagdollSeconds` is the safety net for a body jammed between props that jitters forever.
**Root re-alignment.** The root (with the CharacterController) is still where the character was standing. Before the get-up, it must move under the hips, on the ground, facing the direction the clip expects. Because the hips are a child of the root, moving the root drags the whole ragdoll pose with it, so the script stores the hips' world pose first and restores it afterwards.
**Face up or face down.** `hipsBellyAxis` is the hips bone's local axis that points out of the belly. If its world direction points up, the character lies on its back. Find the axis by selecting the hips bone in Play Mode with the move tool in Local mode.
**Blend in LateUpdate.** After `animator.Play(state, layer, 0f)` and `animator.Update(0f)`, the Animator writes frame 0 of the get-up clip every frame. In `LateUpdate`, the script slerps each bone from the frozen ragdoll pose toward that animated pose over `blendSeconds`. Since LateUpdate runs after animation, the blend wins.
## 5.6 Wiring a test
```csharp
using UnityEngine;
using UnityEngine.InputSystem;
/// <summary>
/// Press K to knock the character down with an impulse from the camera direction.
/// Test only. Not compiled in an editor.
/// </summary>
public sealed class RagdollTestKicker : MonoBehaviour
{
[SerializeField] RagdollController target;
[SerializeField] float impulse = 60f;
[SerializeField] float upward = 0.3f;
void Update()
{
var kb = Keyboard.current;
if (kb == null || target == null || !kb.kKey.wasPressedThisFrame) return;
Transform cam = Camera.main != null ? Camera.main.transform : transform;
Vector3 dir = Vector3.ProjectOnPlane(target.transform.position - cam.position, Vector3.up).normalized;
dir = (dir + Vector3.up * upward).normalized;
Vector3 chest = target.transform.position + Vector3.up * 1.3f;
target.Knockdown(dir * impulse, chest);
}
}
```
Impulse is in newton-seconds. With a 75 kg total mass split over 11 bodies, a 60 N·s push on the chest body is a strong shove; 150+ is a car.
## 5.7 Check
- [ ] Standing: no limb jitters (all bodies kinematic, Ragdoll x Character collision off).
- [ ] K while running: the body keeps forward momentum.
- [ ] Lying on the back: the back get-up clip plays, and the first frame shows no jump.
- [ ] Lying on the front: the front clip plays.
- [ ] After getting up, the CharacterController is back where the body is, not where it was knocked down.
## Sources
- Create a ragdoll (6000.5): https://docs.unity.com/en-us/engine/6000.5/manual/physics-section/physics-overview/ragdoll/wizard-ragdoll-wizard
- Character Joint (6000.5): https://docs.unity.com/en-us/engine/6000.5/manual/physics-section/physics-overview/joints-section/class-character-joint
- `Rigidbody.AddForceAtPosition` (6000.5): https://docs.unity.com/en-us/engine/6000.5/script-reference/unityengine/rigidbody/addforceatposition
- `Rigidbody.isKinematic` (6000.5): https://docs.unity.com/en-us/engine/6000.5/script-reference/unityengine/rigidbody/iskinematic
- `Animator.GetBoneTransform` (6000.5): https://docs.unity.com/en-us/engine/6000.5/script-reference/unityengine/animator/getbonetransform