Despair Physics: Active Ragdoll and Procedural Balance

An active ragdoll on Unity ArticulationBody. Characters walk on their animation and switch to physics when something disturbs them. The physics layer steps to keep balance, staggers, reaches for wounds, grabs walls and falls in several styles. When it is over, the character gets back up or settles.

Folder layout

FolderAssemblyWhat
Runtime/DespairPhysics.RuntimeEverything that ships in a build.
Runtime/Api/The gameplay surface: ActiveRagdoll, IActiveRagdoll, IRagdollBody, RagdollHit, the tuning and profile types (see Public API).
Runtime/Core/Rig definition, parts, effectors (joint drives), the behaviour scheduler.
Runtime/Behaviours/Balance, stepping, hit reactions, falls, get-up, arm and head behaviours.
Runtime/Animation/The animation skeleton (Playables) that the body follows.
Runtime/Locomotion/A small locomotion example (idle, walk, run, stumble, get-up) to read and replace with your own.
Runtime/Debug/Debug view, recorder and incident log for tuning (see Debugging).
Editor/Wizard/DespairPhysics.EditorSetup Wizard, RagdollSetup, rig builder (RagdollRigBuilder).
Editor/Validation/Validator window, RagdollValidator, the ActiveRagdoll inspector.
Editor/Calibration/The Rig Calibrator window and the calibration it runs (see Tuning).
Samples~/Demo Scenes/DespairPhysics.SamplesFifteen demo scenes, seven example profiles and their scripts (import from Package Manager). Safe to delete.
Tests/Editor/, Tests/PlayMode/DespairPhysics.Tests.Editor, .PlayModeEdit-mode and play-mode tests. Safe to delete.

Rig requirements

What a character and its model need before the Setup Wizard can build a ragdoll on them.

The skeleton (the physics rig is a fixed 20-part humanoid layout, see Known limitations):

The model:

The animation:

The project:

Quickstart

  1. Select a humanoid character (in a scene, a prefab, or an imported model) and open Tools > Despair Physics > Setup Wizard. Right-clicking the character in the Hierarchy (Despair Physics > Add Active Ragdoll) or its Animator (Add Active Ragdoll) opens it too. The wizard walks five numbered sections, each with a status icon:

    1. Character: what you picked and how it will be saved. The lock button keeps the wizard on this character while you click bones in the Hierarchy (it locks itself once you pick a bone by hand).
    2. Bones: what the mapper found. Problems are listed first; open Bone for each part to fix them.
    3. Body: mass, collider size and pose. Advanced holds mass by region, which meshes to fit to (untick hair and loose clothing), physics materials, and materials to draw the body with.
    4. Animation: the model the hidden animation skeleton is made from, and locomotion clips.
    5. Preview and build: Preview builds on a hidden copy and draws the colliders in the Scene view; Build previews first if you haven’t, and asks before anything it can’t undo.

    On a scene object or prefab instance the whole build is one undo step; a prefab is built and saved; a model gets a new prefab variant next to it. Remove Ragdoll takes it off again. The rest of this section is what the wizard does, for scripting it yourself.

  2. Push it: import the Demo Scenes sample (Tools > Despair Physics > Import Demo Scenes…, or Package Manager > Despair Physics > Samples), open 01 Quickstart, press Play and click the character.

  3. Check every ragdoll in the open scenes with Tools > Despair Physics > Validator. The ActiveRagdoll inspector shows the same findings, with Fix buttons where a fix is safe, and in Play mode what the body is doing.

Demo scenes, in reading order

Each scene has an on-screen panel saying what it shows, its controls and which script to read, and Previous / Next buttons to walk the list.

SceneShowsRead
01 QuickstartOne character: push it, kill it, watch the events.ClickToPush, RagdollEventLog
02 Build a RagdollThe Setup Wizard and the Validator on a raw model, with no code.BuildARagdollGuide
03 HitsA submachine gun and real health: damage by body part, and only the round that empties the health is sent as lethal.SubmachineGun, RagdollHealth, HealthBar
04 Animation HandoffWho drives the body, and when it changes hands: a walk, a shove, a knock-down, a teleport, a kill. A strip shows who drove the body over the last 20 seconds.HandoffDemo, DriverStrip
05 TerrainLocomotion over stairs, a slope, a ledge and a moving platform.TerrainWalker, PlatformMover
06 ReactionsNine bays, each the same character twice with one reaction on and off, and a sample component (RaiseArmWhenHit) that reacts to hits. A camera tour hits one pair at a time.HitComparison, ShowcaseDirector, RaiseArmWhenHit
07 ProfilesThe seven example profiles and your own, side by side, taking the same five hits.HitComparison, ProfileShowcase
08 DialsThe seven dials of a profile on three characters: a tour, then sliders of your own for two setups (A and B, picked with a button) shoved side by side with the defaults, and recipes made with SetDial alone.DialsDemo
09 Rig ScalingOne character at 1x, 2x and 0.6x, untouched, scaled to the rig and calibrated, shoved alike.HitComparison
10 Locomotion OptionsThe same patrol and shove with clips, a Mecanim controller and a locomotion of your own.PatrolLocomotion, LocomotionDemo
11 Debug ToolsThe debug view, the recorder, the incident log and interpolation on one shoved character.DebugToolsDemo
12 BenchmarkAdd characters until your frame budget runs out; what each one costs.RagdollBenchmark
13 MobileThe benchmark with cheaper physics settings and the Mobile profile, for phones.MobileTuningDemo
14 PlaygroundA stress-test arena: walk a character (W A S D), enter any state with the number keys, and meet big stairs, a blender, a sweeper, a wrecking ball, cannons, loose props and wandering pedestrians.PlaygroundPlayer, CannonTrap, KinematicSpinner, PedWanderer
15 Physics InteractionsLoose things and moving traps in one room. Throw balls at two characters side by side, one on a profile with Feel.IgnorePropImpacts (the same impact and impulse, a different reaction); pedestrians in a pit with one slow blade; pedestrians climbing a slope while massive balls roll down it. Crates, barrels and balls can be grabbed with the mouse.BallImpactProbe, SlopeClimber, SlopeBallDropper, PhysicsInteractionsDemo, RagdollDragger

Terms

Public API

The types below are the package’s public surface, and semantic versioning covers them. Everything else is internal: the behaviours (DynamicBalancer, StayUpright, Shot and the others), the effectors, the animation layers and the rig tables. They change between releases without notice.

GroupTypes
Talking to a characterActiveRagdoll (and its Events), IActiveRagdoll, RagdollState, RagdollHand, GripKind, RagdollHit, RagdollHitRecord, RagdollBalance, IRagdollBody, RegionPose (from PoseRegion, see Tuning)
Driving the body from gameplayBalanceSteering (on MarionetteCharacter.Steering, see Walking from gameplay), and on ActiveRagdoll: ForceGetUp, GetUpForced; on MarionetteCharacter: RunawaySpeed, RunawaySpin
RulesActiveRagdollTuning, ActiveRagdollProfile, ProfileDial, ReactionFeel, BalanceLimits (and BalanceTest), BalanceGains, KnockStates, ReactionKind, ReactionModule and the reactions that derive from it (WallGripModule, StaggerModule and the rest, listed in ActiveRagdollTuning.Modules)
ComponentsMarionetteCharacter, MarionetteAnimator, MarionetteLocomotion (and LocomotionState), MarionettePart, MarionetteInterpolation
Your own locomotionILocomotion, LocomotionHost, GetUpResult, BodyMask (see Extending locomotion)
Your own behavioursRagdollBehaviour, and on MarionetteCharacter: AddBehaviour, StartBehaviour, StopBehaviour, RemoveBehaviour, BehaviourReported (see Your own behaviours)
Body set-upOn MarionetteCharacter: GroundLayers, PhysicsScene, JointLimits, SetJointRange, GetJointRange, InertiaGains, ApplyInertiaGains, RefreshMasses; on MarionetteAnimator: GhostBones, CopyFingers, PauseWhileUnused, Paused, PoseChanged
SteppingRagdollSimulation (Stepping, AutoStep, MaxTravelPerSubstep, MaxSubsteps, ImpactLayers, LastSubsteps, SubsteppedSteps, SubstepStarting, InterpolationAlpha, Step, Simulate, AfterSimulation), RagdollStepping, RagdollSimulationSettings (see Stepping physics yourself)
Where the pose comes fromIPoseSource, PlayingClip, ClipMixerSource (with its ClipState, BlendMixerState and AnimState handles), MecanimPoseSource, AnimatorParameterDriver, and on MarionetteAnimator: Source, SetSource, ClipMixer, Controller, UseModelAvatar, Playing, BeforeEvaluate, Animator, Model, Bone, PathOf, NativeFrameEvent
Scale and tuning aidsRagdollLod, RagdollTier, RagdollTierSettings, RagdollLodMode, RagdollLodSettings, RagdollStats, RigDefinition (part indices and masses, ParentOf, MaskOf, RadiusOf)
DebuggingMarionetteDebugView, MarionetteRecorder, MarionetteIncidents
Editor scriptingRigMapper, RigMapping, RigMapOptions, and the public types of DespairPhysics.Editor

Even on these types, only the members that are public are supported: much of MarionetteCharacter is internal. The Demo Scenes sample, the editor assembly and the package’s own tests see the internals (InternalsVisibleTo), so sample code that reaches below this list, such as the Reactions scene’s RaiseArmWhenHit component (it moves the arm with the internal arm pose), does not carry over to your project as it stands; move the arm with Aim, a region pose or a RagdollBehaviour instead. Your game does not need them: Tests/PublicApi is a test assembly that is not on that list, and it implements a locomotion, a pose source and a Mecanim-driven body from the types above alone.

What the wizard does

  1. Get a humanoid character. Its bones are found by RigMapper, from the first of these that fits:

    • its Humanoid avatar;
    • a naming preset: Mixamo (any mixamorig prefix), Unreal mannequin, Character Creator (CC3/CC4), Daz Genesis 2/3/8/9, VRoid, Blender Rigify (DEF- bones), Blender Auto-Rig Pro (raw deform export; its Humanoid export uses Unreal names), 3ds Max Biped (any biped name);
    • only if you pass RigMapOptions { UseNameHeuristics = true }: words in the bone names (leg_thigh.L, L_shin). This is unreliable, since a guess can pass every check and still pick a helper bone. Review the mapping before building.

    The torso can have one to six or more spine bones between the hips and the neck. The chest is the spine bone the clavicles hang from. With fewer than three bones, the missing segments merge into the chest joint. With more, the extra bones ride along unsimulated.

  2. From an editor script, call RagdollRigBuilder.Build(instance, new RagdollRigBuilder.Settings { AnimationSkeleton = sourceModel, ... }). The builder first normalises the instance: it turns the skeleton upright to face +Z, poses an A-pose into T-pose, and moves the soles onto the origin. It then sizes each collider from the skinned mesh, falling back to the bones and the character’s height, and shares the mass. Set TotalMass, or leave 0 to scale 94 kg by (height / 1.8 m)³. RegionMass multiplies regions, and VolumeMassWeight shares mass by collider volume instead of the anatomical table (for cartoony proportions). Muscle strength scales with mass × height. Pass a list as Settings.Report to see what was done. Finally it adds an articulation link, collider and MarionettePart on each rig bone, then MarionetteCharacter, MarionetteAnimator and ActiveRagdoll.

  3. Optionally, add MarionetteLocomotion and assign its clips (Idle, Walk, Run, get-ups). Without it, the balancer holds the body up on its own. MarionetteLocomotion is deliberately small: it shows how a locomotion script drives the animation skeleton, hands the body to the balancer and takes it back. See Extending locomotion to grow it into the script your game needs.

For a Generic rig that no preset maps, the wizard lists every part with an empty bone field: fill them in by hand (the lower spine bones are optional and merge into the chest when left empty). In code, set RigMapping.Bones and call RagdollSetup.Revalidate before building.

To make a character from scratch in Blender that maps with no manual steps, see HowToCreateSampleCharacterInBlender.md.

Locomotion clips and root motion

MarionetteLocomotion has to know how fast the body travels while a Walk (or Run) clip plays. A walk animation is one of two kinds, and each has exactly one setup:

The clip…Set up
Moves: the animation carries the character forward (root motion)Generic rig: in the model’s import settings, Rig tab, set Root node to the pelvis, and leave the Root Transform options alone. Humanoid rig: bake the root rotation, see Locomotion clips and root motion. Nothing on the component.
Stays in place: the legs move, the body doesn’t (Mixamo’s “In Place”, most asset-store packs)Set InPlaceWalkSpeed (and InPlaceRunSpeed) on MarionetteLocomotion. Nothing in the import settings.

That is all of it. You don’t turn on Apply Root Motion anywhere: the package plays the clips on a hidden copy of the skeleton, switches root motion on for that copy itself, and carries the physical body along.

Clips that move. The Walk clip’s average ground speed (AnimationClip.averageSpeed, in m/s) is the walk speed, and the body steps exactly as far as the clip does, so the feet don’t slide.

Humanoid clips. On a model imported as Humanoid (see the avatar rules in Extending locomotion), Unity works the root out from the avatar’s body, so there is no Root node to set. What you choose instead is which parts of the root go into the pose (Bake Into Pose) and which stay as root motion. The package takes two things from a locomotion clip’s root motion: the travel along the ground, and the turn about the vertical axis. It adds the clip’s turn to the body’s heading on every step, on top of its own steering, and it ignores the root’s height, standing the body on its lower ankle. A clip with a keyframed root rotation, or one that follows the swing of the hips and shoulders (Based Upon: Body Orientation), would therefore keep turning the character as it walks, and the steering would fight it. Bake the rotation so it stays in the pose and the turn the package sees is nil.

ClipRoot Transform RotationRoot Transform Position (Y)Root Transform Position (XZ)
Walk, Run (moving)Bake Into Pose on, Based Upon OriginalBake Into Pose off, Based Upon OriginalBake Into Pose off, Based Upon Original (this is the travel)
Idleon, Originaloff, Originaloff, Original
Get-up (both)on, Originalon, Originalon, Original

This table was tested in the editor with the sample character (DespairRig). How a clip keys its root differs from one animation pack to the next, so a different pack may need different Root Transform settings: if a clip turns the character, drifts or sidesteps while it plays, change what is baked on that clip. Humanoid clips are taken as authored in the character’s own frame, with no heading correction (a Generic clip gets one), so a Walk must head straight along the character’s forward once the rotation is baked. Watch for a walk that sidesteps, and fix it in the source animation.

A clip without root motion has no ground speed. The character turns toward its goal but never moves, and the console says so on start: the clip ‘Walk’ has no root motion, so the character would not move. Either give it root motion as above, or treat the clip as in place:

In-place clips work without re-importing anything. Set MarionetteLocomotion.InPlaceWalkSpeed (and InPlaceRunSpeed if you have a Run clip) to the speed the clip’s feet cover, in m/s, and the body travels at that speed while the clip plays, scaled by the blend and the clip’s playback rate. Guess it by watching the feet: too high and they skate forward, too low and they slide back. Typical values are about 2 m/s for a walk and 3.5 to 5 m/s for a run.

If you write your own locomotion script, the same applies: the animator hands the root motion of what is playing to FollowRootMotion, so a clip with none moves nothing until you give it a speed.

Extending locomotion

There are three ways to take locomotion further, from least to most work. None of them needs the package moved into your Packages folder.

1. Drive MarionetteLocomotion from a component of your own. It walks to a point in a straight line (MoveTo, Stop, Goal, State):

2. Write your own locomotion. Strafing, facing a target, stances, one-shot moves (roll, jump) and your own pathing are more than a point to walk to: they are a different locomotion. Put a component that implements ILocomotion on the character (MarionetteCharacter.Locomotion finds it) and the character drives it: Begin(host) once at start, PreStep(dt) every physics step before the animation is evaluated, and Disturb, Hit, Suspend, Resume and StartGetUp when something happens to the body. You move the body through the LocomotionHost that Begin hands you:

The animation’s pathTargetYaw, MaxTurnRate, PathSpeedScale, PathVelocity, RootYaw, Nudge, Anchor, PinRegion, FreeJointPull, IsPinned, IsFollowing
What pushed the bodyPinKick, GroundDrop, ChestError, NavMeshBlocked, TouchingObstacle, TouchingStep, ObstacleAway
Handing the body overFollow(blendTime), ReleaseToBalancer(), StopFollowing(), PoseFromAnimation(), BalancerActive, BalancerStableTime, IsUpright
Getting upStartGetUp(clip, faceDown, rate, releaseFade), BuildFallbackGetUp(faceDown), FallbackGetUpPlays (always true: the fallback is Generic bone curves, or muscle curves on a Humanoid character), LieDownInstead(), AbortGetUp(), StopGetUp(), IsFaceDown, IsGettingUp
What came of itGetUpFinished, GetUpFailed, BalanceLost
Hit tuning from the profileStumbleSpeed, StumbleImpulse, StumbleHardHit
public sealed class MyLocomotion : MonoBehaviour, ILocomotion
{
    public AnimationClip Idle;
    LocomotionHost host;

    public LocomotionState State { get; private set; }
    public float Speed => 0f;

    public void Begin(LocomotionHost h)
    {
        if (host != h) { host = h; h.BalanceLost += _ => State = LocomotionState.Off; }
        host.Animator.ClipMixer.Play(host.Animator.ClipMixer.GetOrCreate(Idle), 0f);
        host.Follow();                                  // the animation carries the body
        State = LocomotionState.Following;
    }

    public void PreStep(float dt) { /* choose clips, steer: host.TargetYaw = ... */ }
    public bool Disturb() { host.ReleaseToBalancer(); State = LocomotionState.Recovering; return host.BalancerActive; }
    public bool Hit(Vector3 impulse) => Disturb();
    public void Resume() { host.ReleaseToBalancer(); State = LocomotionState.Recovering; }
    public void Suspend(bool keepBalance = false) { host.StopGetUp(); host.StopFollowing(); State = LocomotionState.Off; }
    public GetUpResult StartGetUp()
    {
        host.StartGetUp(host.BuildFallbackGetUp(host.IsFaceDown), host.IsFaceDown);
        return GetUpResult.Started;                     // or LieDown for a body that can't stand
    }
}

MarionetteLocomotion is the reference: it is written with nothing but this interface, the host and the clip mixer, so copy it into your project and change it. Tests/PublicApi has a minimal one that stands, falls and gets up. A body that can’t stand (no legs) answers StartGetUp with GetUpResult.LieDown after taking its lying stance itself. A hit arrives once per bullet (once per blast for a shotgun); Hit may stumble on or fall back to Disturb.

3. Choose where the pose comes from. The package does not own an animation system, it consumes one. The MarionetteAnimator evaluates a playable graph once per physics step from a pose source (IPoseSource):

Clips baked on the character’s own skeleton carry the MarionetteAnimator.NativeFrameEvent marker so no root-frame correction touches them. A character’s clips are all Generic or all Humanoid. A Humanoid clip does nothing on a Generic avatar, and a Generic clip plays wrong on a Humanoid one. The animation skeleton gets a Generic avatar built at start, unless the model has a Humanoid avatar and every clip in MarionetteLocomotion and the Controller is Humanoid (the package’s own get-up, played when a get-up clip is missing, is built in the avatar’s kind: muscle curves on a Humanoid character). Then it keeps the model’s avatar, and MarionetteAnimator.UsesHumanoidAvatar reads true. Tick UseModelAvatar to keep it whatever the clips are, for a pose source of your own that plays Humanoid clips. Mixed clips are named on start, in the console and in the Validator. Humanoid clips are taken as native-frame. Check the root motion in your project: the Root Transform settings under Locomotion clips and root motion were tested in the editor on the sample character, and one play-mode test checks that a Humanoid clip poses the animation skeleton, but other animation packs may key their root differently.

Your own behaviours

RagdollBehaviour is the way into the scheduler that runs the built-in behaviours (balance, stagger, get-up…). Derive from it, set its Mask (the joints it wants) and fill in Tick; OnStart and OnStop are optional. Every physics step while it runs, after the animation is evaluated and the body sensed and before the muscles are written, its Tick sets joint targets and springs for the joints it owns:

sealed class SaluteWhenHit : RagdollBehaviour
{
    public SaluteWhenHit() => Mask = BodyMask.RightArm;
    protected override void Tick(float dt)
    {
        if (!Owns(RigDefinition.UpperArmR)) return;
        SetStiffness(RigDefinition.UpperArmR, 12f);
        // On top of the animation: lift the arm a little further than the clip has it.
        SetTarget(RigDefinition.UpperArmR, AnimationTarget(RigDefinition.UpperArmR) + new Vector3(0f, 0f, 0.6f));
    }
}

character.StartBehaviour(new SaluteWhenHit());   // adds it, then starts it

It comes after every built-in behaviour, so while it runs it wins the joints in its mask; of two of yours, the one added last wins. Angles are in radians: x is flexion, y the side lean, z the twist (hinges use x). JointAngles, JointSpeeds, AnimationTarget and SetGravityCompensation read and shape the rest; Report raises MarionetteCharacter.BehaviourReported. A behaviour that only sets targets can return true from RunsWhileAnimated and keep running on a body playing as animation only; otherwise starting it hands the body back to physics. A restart (ResetToStanding, pooling, a blow-up) stops every behaviour, yours included: start yours again from MarionetteCharacter.Restarted if it should run from the start.

Stepping physics yourself

RagdollSimulation.Stepping says who runs physics. Set it from code, or with a Ragdoll Simulation Settings component in the scene (Add Component > Despair Physics), which applies its values while it is enabled. Substepping is off by default: switch to Substepped if bodies in your game are thrown, shot or dropped hard enough to hit something at 20 m/s or more, or if you see a body twist itself apart on impact.

Each character probes the ground in its own scene’s physics scene (MarionetteCharacter.PhysicsScene), on GroundLayers: leave out layers of things that are never floor (foliage, a vehicle’s interior hull).

Talking to a character

Gameplay talks to a character through IActiveRagdoll (implemented by ActiveRagdoll) and reads the body through IRagdollBody (implemented by MarionetteCharacter). Health, damage and scoring belong to your game. The ragdoll only decides how the body reacts.

if (!MarionettePart.TryGetPart(hit.collider, out var part)) return;   // not a ragdoll
var ragdoll = part.GetComponentInParent<IActiveRagdoll>();
bool kills = myHealth.Apply(damage);   // your game's rule
ragdoll.Hit(new RagdollHit(part.Index, hit.point, ray.direction,
    impulse: 60f, killImpulse: 90f, spreadToBody: 0.1f, lethal: kills));

Commands

CallEffect
Hit(RagdollHit)The push, plus the reaction it starts: stagger, wound reach, leg buckle, standing death or drop. RagdollHit.Kind says what hit: Bullet (the default: a snap of the spine, a tick back, a whip of the neck, the push in a 0.05 s burst), Blunt (a punch, a bat, a car: a longer push, no tick back, more through the whole trunk), Shove (a long steady push with hardly any snap) or Blast.
KnockDown()A standing body goes down alive. It gets up later if it has locomotion. Does nothing unless the body is Active; read State to see whether it went down. Returns nothing, so it can be wired to a UnityEvent.
KnockDown(direction, impulse)The same, but the body falls the way direction points (flat), shoved by impulse N·s along it (0 = only the direction it goes down).
GetUp()Starts a downed body’s get-up now, whatever AutoGetUp and the get-up delay say. False when the body is not downed, is still falling or hanging, or has no locomotion to play the get-up. Set AutoGetUp = false to keep a body down until the game calls this.
ForceGetUp()Gets a downed body up now and sees it through: it doesn’t wait for the body to lie still, and until it stands nothing that runs into it (balls, other bodies, a hit while getting up) aborts the get-up or starts a reaction. Physics still pushes it. A get-up already under way becomes forced. GetUpForced reads true meanwhile: a game’s own collision handlers (a launch pad, a conveyor) should check it too. Kill() and ResetToStanding() still win. False when the body is not downed, has no locomotion, hangs from a ledge or falls from a height: try again later. For a body on a belt, a slope or under a rain of props, which the automatic get-up would leave lying for good.
Kill()Goes limp at once, from any state. Does nothing to a body that is already Dead. Returns nothing, so it can be wired to a UnityEvent.
Revive()Brings a dead body back to life where it lies, keeping its pose: it is Downed and gets up (or waits for GetUp()). A dying body still on its feet is let off and is Active again. Nothing is moved or re-posed, unlike ResetToStanding().
Disturb() / SustainBalance()Something grabbed the body. Hand it to physics, then keep it stepping while it is held.
LookAt(target)Where the head looks when nothing else draws it.
Aim(hand, target, barrelInHand), AimRecoil(), ReleaseAim()Swing an arm out and point a held object.
HandFree(hand), SetHandBlocked(hand, blocked)Whether a hand is whole and idle, and taking a hand out of use (a lost arm, something in the hand): a blocked hand takes hold of nothing. Hands are always a RagdollHand (Left or Right). Standing back up gives both back.
KnockState, SetKnockStates(canKnock, canBeKnocked)What the body counts as for a bump, and which states knock others or can be knocked (the Knock reaction).
Teleport(position, facing, keepVelocity)Moves the whole body in any state. Never move the root transform of a live character.
ResetToStanding()Back to Active, standing clean on the root transform, every reaction forgotten (a blocked hand included).
SetSeed(seed), ClearSeed()Draw the body’s random choices (which hand, how long, which way down) from a stream of its own, seeded for replays and networking, or back from Unity’s global Random.
Blast(centre, radius, impulse, killImpulse, lethal, lethalRadius, lift, occluders), ActiveRagdoll.BlastAll(...)A radial hit: every part inside radius is pushed away from the centre by its own distance (the near side harder than the far side, so the body turns), tilted up by lift (0.3 by default), and the body reacts once, led by the part nearest the centre. occluders is a layer mask: a part a straight line from the centre can’t reach past those colliders is left out (empty by default: nothing blocks the blast). BlastAll does it to every ragdoll in the scene and returns how many it reached.

Pooling

Disable a character, move its root transform to the spawn point, and enable it: on its second physics step it stands up clean there (state Active, full strength, tuning reset). The wait is for PhysX to put the links back in the scene. MarionetteCharacter.Restarted fires when it does.

State and events

State is one of Active, Dying, Downed or Dead. StateTime, GettingUp, GetUpForced, LastHit and Balance (tilt, steps left, staggering) are readable at any time.

EventRaised when
StateChanged(from, to)State changes.
Struck(hit)A hit reached the body.
LostBalanceA living body can no longer catch itself and staggers.
FallenA living body went down.
RecoveredA stagger caught itself, or the body got up.
RevivedRevive() brought a dying or dead body back.
DiedThe body entered Dead.
SettledA corpse came to rest (after SettleTime) and may sleep.
GetUpStartedA downed body started its get-up, by itself or by GetUp().
Landed(landing)A body that fell from a height hit the ground (its high fall ended). RagdollLanding carries Speed and DownSpeed (m/s at touchdown, for fall damage) and Band: Soft (taken on the legs, the body stays Active and Recovered is raised), Hard (down on the knees and hands, Downed for a short while, no writhing) or Crash (flat on the floor, writhing, the long get-up). The bands are set by the HighFall reaction’s SoftLandingSpeed and CrashLandingSpeed.
Gripped(hand, kind)A hand took hold of a wall or a ledge (GripKind.Wall or Ledge).
GripReleased(hand, kind)A hand let go, was torn from its hold, or the body died.

Every one of these 12 events is also exposed as a UnityEvent under Events in the ActiveRagdoll inspector, raised right after the C# event of the same name.

Walking from gameplay (BalanceSteering)

MarionetteCharacter.Steering lets a game move a character by physics instead of by its animation: a player character in a physics game, a body that has to walk over whatever the level throws at it. The balancer keeps the body up and places the feet; the game says where to go.

var steer = ragdoll.Character.Steering;
ragdoll.Disturb();                 // hand the body from its animation to the balancer
steer.Active = true;               // keep it there: it never goes back to the animation on its own
steer.PlanSteps = true;            // walk on steps placed on purpose, not only steps that catch a fall
steer.Velocity = input * speed;    // wanted ground velocity (m/s, world)
steer.Facing = input;              // wanted heading (zero: keep the one it has)
...
steer.Release();                   // done: the balancer behaves as without steering

The pace push, as the tests and the parkour demo do it:

void FixedUpdate()
{
    var c = ragdoll.Character;
    var steer = c.Steering;
    if (!steer.Active || !steer.PlanSteps || !(grounded)) return;   // grounded: your own foot check
    Vector3 v = c.CentreOfMassVelocity; v.y = 0f;
    Vector3 force = Vector3.ClampMagnitude((steer.PacedVelocity - v) * 4f, 3f) * c.TotalMass;   // gain 1/s, cap m/s²
    c.Root.AddForce(force * 0.4f);
    c.Part(RigDefinition.Chest).Body.AddForce(force * 0.6f);
}

With RagdollStepping.Substepped, add the same force again from RagdollSimulation.SubstepStarting (see Stepping physics yourself). Ramp Velocity up and down (the demo uses 6 m/s²) rather than asking for a new one at once: a stop or a turn at a run asked for in one step throws the body over.

Measured on the test rig (the bare 1.8 m test skeleton at default tuning, SteeringPlayModeTests): asked for 1.2 m/s with the push above it walks 1.3 to 1.45 m/s; with a gain of 1.5 it runs about 1.55. Asked for less than about 1 m/s it walks at about 1 m/s whatever the push, and asked for 1.8 m/s with the push it can fall. It climbs and walks down six stairs of 15 by 30 cm at 0.8 m/s asked, lands a hop of about 1 m on its feet, and stays up. The pace a rig holds depends on its tuning: tune the step time, CaptureTimeScale and the push on your own rig, and check them at the paces your game asks.

Stair stepping (StairStepping, on) is how planned steps read the ground, and only planned steps do: a body shot, shoved or knocked steps as physics sends it, wherever its steering is, so the ground’s shape never props up or reshapes a reaction. With it on, a step lands with the whole sole on one tread or one even slope, not across a stair’s edge (it slides along the foot by up to 20 cm to find one); a step onto a stair or a ledge is put down on the level above with the sole past its edge, one level per step; a swinging foot keeps clear of the nosings it passes over and comes down onto a lower tread only at the end of its swing; a foot standing on a slope tilts to lie on it (at most 0.45 rad); and a swinging foot whose path crosses a riser doesn’t collide with GroundLayers until the last quarter of its swing, so a toe that would scrape a nosing doesn’t snag (colliders on those layers don’t stop such a foot meanwhile). The pace, step-up and climbing settings above come with it. Off, planned steps land on whatever floor is under them, as catching steps do. Measured down six stairs of 15 by 30 cm at 0.8 m/s asked (5 trials): stair stepping missed its foot targets by 7 to 12 cm on average with the trunk tilted 12° at worst; plain steps, 8 to 9 cm and 8°, in about 3.6 s against 5.6 s (stair stepping slows the walk to StairPace).

Going down stairs (StairSteppingDown, off) the ground-reading is built for climbing and only holds the body back: short strides land on the tread it already stands on and the trunk is held upright out over the drop. So by default, while the walk heads down a flight (stairs within TerrainLookahead, nothing ahead higher than the floor under the body, the far end lower), planned steps are plain ones, exactly as with StairStepping off, and TerrainPace stays 1. It switches on as soon as the descent is seen and off 0.4 s after it is gone; it waits while a foot is passing through a step (made solid in there, the foot would be fired out). A ramp down has no stairs and keeps the ground-reading steps; a flight that goes down and then up again within TerrainLookahead counts as a climb. Turn StairSteppingDown on for the ground-reading steps both ways.

Tuning

Performance

All characters are stepped from one hidden manager in FixedUpdate, with no garbage per step (checked by play-mode tests while standing, while reacting to a hard hit, and on the animated sample character; the count comes from the profiler’s “GC Allocated In Frame” counter, since GC.GetAllocatedBytesForCurrentThread reads 0 under Unity’s Mono). In the Profiler, look for DespairPhysics.Step, split into .Tiers (picking each character’s level of detail, with the obstacle checks of characters playing as animation, cast as one batch), .GroundProbes (every character’s foot rays, cast as one batch), .Animation, .Sense, .Behaviours (with one marker per behaviour, such as DespairPhysics.DynamicBalancer), .Drives and .Guard; DespairPhysics.Interpolation is the drawing between steps.

Measure with Maximum Allowed Timestep (Project Settings > Time) equal to the fixed step, so one physics step runs per frame: otherwise a slow frame runs two or three steps to catch up and the numbers don’t compare. The Benchmark sample does that while it runs (One Step Per Frame).

What keeps a character cheap:

Level of detail

Each character runs at a tier, picked every physics step (MarionetteCharacter.Tier, counts in RagdollStats):

TierWhenCost
FullNear the viewer (main camera, or RagdollLod.Viewer), within the budgetEverything
ReducedBeyond ReducedDistance (25 m), or past the budgetRagdollLod.Reduced: by default at most 4 / 1 solver iterations, and the animation and ground probes every other step
AnimatedUndisturbed, and the settings allow it (off by default)No physics body: the visible skeleton is played by an Animator of its own at the frame rate (or, where it can’t be, posed from its joints every physics step)
DormantA settled corpse whose links all came to restNot stepped; wakes when hit, grabbed, moved or knocked

Set it up from a scene with a Ragdoll LOD Settings component (Add Component > Despair Physics), or from code through RagdollLod. The component applies its values while it is enabled, and puts back the ones it replaced when it is disabled.

Animation only

An undisturbed character can switch its physics body off and play its animation straight, like a plain animated character. The link components are disabled, and the animation graph that drove the hidden animation skeleton is moved onto an Animator on the visible skeleton (RagdollLod.AnimatedOnAnimator, on by default). Unity updates it once a rendered frame with every other Animator, on its worker threads. The package’s own work for the body drops to the locomotion’s input, the ground probes and the wake checks each physics step, and placing the hips on the path and fitting the feet to the ground each frame. Its colliders stay where the body is, so raycasts and bullets still find it.

“Undisturbed” means all of these held for AnimatedSettleTime (0.5 s):

It goes back to full simulation at once, before the cause acts on it, and moves on as the animation was moving it:

A body woken by a hit takes it as one that was simulated all along (a play-mode test compares the two).

Turn it on with RagdollLod.AnimatedDistance: the distance beyond which undisturbed characters play as animation. Infinity, the default, means never, and 0 means always. On the component, set Animation Only to Beyond Distance or Whenever Undisturbed. It suits a cinematic game such as a shooter, where bullets, blasts and grabs are what move bodies. It doesn’t suit a game where every bump must show (dodging projectiles, a physical brawler). Leave it off there, or set NeverAnimated on the characters that matter.

While a character is animated:

Measured on 32 characters in the 12 Benchmark room (Editor play mode, 50 Hz physics, PerfBench in the dev assets), playing as animation only, standing and walking:

Animated tierRagdoll step, per physics stepPer rendered frame (Animator, hips and feet)
Through the joints (as before)4.1 ms0.25 ms (interpolation and frame callbacks)
On the visible Animator0.93 ms standing, 1.15 ms walking, of which 0.34 ms is the wake checks both share0.62 ms (Unity’s Animator update 0.44 ms, the package’s 0.18 ms)

(The visible Animator row was 1.35 ms, 0.66 of it the wake checks, before the obstacle checks were batched and the ground fitting kept its rays on a standing body; the joint path wasn’t measured again.) At 60 frames a second that is about half the main-thread time of the joint path; at 200 frames a second, as the Editor ran, about a sixth less, since the Animator runs every frame.

Measured with the Benchmark presets

The 12 Benchmark scene is a short tour of these settings. It switches presets with the number keys 1 to 4 and shows the ragdoll step plus PhysX measured for each. These are 16 standing characters with the random shoves off, measured in Editor play mode, per physics step:

PresetTiersRagdoll stepPhysics stage
1 Everything simulated16 Full3.0 to 3.4 ms1.4 ms
2 Budget of 8 (the rest Reduced, animation every other step)8 Full, 8 Reduced2.8 ms1.4 ms
3 Animation only when undisturbed16 Animated0.6 ms0.2 ms
4 Budget of 8 and animation only past it8 Full, 8 Animated2.0 ms0.8 ms

With the scene’s shoves on (S, each body shoved every 3 s), few bodies stay undisturbed long enough to play as animation, and the presets cost about the same as preset 1. Animation only pays off for bodies that are left alone most of the time.

MarionetteCharacter.SetSolverIterations sets a body’s Full-tier iterations (the Mobile sample uses 4 and 1). RagdollStats reports the last step’s cost for on-screen readouts.

Measured budgets

Benchmark sample on its own settings: characters shoved at random so they keep balancing (each every 3 s), 50 Hz physics, one physics step per frame. Editor play mode on an AMD Ryzen 7 3700X, Unity 6000.3; a player build will be faster. The ragdoll step is the package’s own work; PhysX is the physics solve of the whole scene. At 64 the farthest characters are past 25 m and run Reduced.

CharactersRagdoll stepPer characterPhysX per stepFrame rate
163.3 ms205 µs1.7 ms185 fps
326.2 to 6.8 ms195 to 215 µs2.9 ms100 fps
64 (about 52 Full, 12 Reduced)11.6 to 12.9 ms180 to 200 µs3.3 to 4.6 ms35 to 43 fps

So plan on about 0.2 ms of CPU per balancing character per physics step, plus Unity’s own physics. The numbers depend on the machine, the Unity version and how hard the characters are being shoved.

These are Editor numbers. Measure on the devices you ship to: build the 12 Benchmark and 13 Mobile scenes into a player, add characters with Up until the frame-time warning shows, and keep a margin below that for the rest of your game. Both scenes hold up to 289 and 169 characters respectively.

Interpolation

Physics moves the bones once per fixed step (50 Hz), so on a faster display the same pose is drawn for several frames and then jumps. ArticulationBody has no interpolation setting (that is Rigidbody’s), so the package has its own: MarionetteInterpolation draws every part a fraction of the way between its last two physics poses. It adds up to one step (20 ms at 50 Hz) of latency to what is drawn, and costs one transform write per part per frame while the body moves, nothing once it has settled. Every character is drawn in one transform job across the worker threads, each bone in its parent’s space.

Other Rigidbodies with RagdollStepping.Substepped. Unity interpolates a Rigidbody only through steps it simulates itself, and a step the package runs in substeps is simulated from script. For a Rigidbody that must stay smooth through impacts (the player’s vehicle, a prop the camera follows), set its interpolation to None, draw it with a separate visual object (the mesh, not a child of the body), and move that visual between the body’s last two physics poses:

public sealed class PhysicsPoseSmoother : MonoBehaviour
{
    public Rigidbody Body;
    Vector3 fromPosition, toPosition;
    Quaternion fromRotation = Quaternion.identity, toRotation = Quaternion.identity;
    bool started;

    System.Collections.IEnumerator Start()
    {
        var afterPhysics = new WaitForFixedUpdate();
        while (true)
        {
            yield return afterPhysics;   // after each fixed step's simulation, substeps included
            if (Body == null) continue;
            if (!started) { fromPosition = Body.position; fromRotation = Body.rotation; started = true; }
            else { fromPosition = toPosition; fromRotation = toRotation; }
            toPosition = Body.position;
            toRotation = Body.rotation;
        }
    }

    void LateUpdate()
    {
        if (!started) return;
        float a = Mathf.Clamp01((float)((Time.timeAsDouble - Time.fixedTimeAsDouble) / Time.fixedDeltaTime));
        transform.SetPositionAndRotation(Vector3.Lerp(fromPosition, toPosition, a), Quaternion.Slerp(fromRotation, toRotation, a));
    }
}

It draws one step behind, as Unity’s interpolation does. In the tests (SubstepInterpolationPlayModeTests), with every step in substeps, it moved evenly on more than 90% of frames where Unity’s own interpolation did not. Alternatively, keep substeps away from those bodies: ImpactLayers decides what counts as something to hit, and with Stepping on Unity nothing is substepped.

Timestep and time scale

Recommended: 50 Hz (Fixed Timestep 0.02) or faster. 30, 50, 60 and 120 Hz are tested; at 30 Hz bodies stand but sway more. Slow motion and pause (Time.timeScale 0.1 and 0) are tested. The validator flags a timestep slower than 50 Hz and offers to change it.

The tuning means the same thing at any fixed timestep: the muscles’ torque ceiling, the ground and foot smoothing and the damping of the helper forces are per second, matched to their 50 Hz values; the yaw damping is taken implicitly, so it can’t overshoot a coarse step. Hit reactions, get-up timing, corpse settling and wall-grip scouting all run on the physics clock, so a seeded character plays out the same at any frame rate.

Play mode without domain reload

Supported. Static state (the update manager, MarionetteCharacter.All, RagdollLod, RagdollStats, MarionetteIncidents) is reset on entering Play mode. The play-mode tests pass with domain and scene reload off.

Unity 2022.3: standing bodies drift

On Unity 2022.3 a character that stands on its balance alone can slowly slide and turn on the spot, even though nothing touches it. The same scene on Unity 6 stands dead still. Raising the physics solver’s position iterations to about 20 fixes it on 2022.3. The package doesn’t do this for you.

Who it affects

Bodies balancing with no animation pinning them: a ragdoll without MarionetteLocomotion, or any body handed to the balancer and left standing there (after a shove it caught, or after getting up with no locomotion to take it back). A body walking on its animation is pinned to its root motion, so it rarely shows the drift. Unity 6 is not affected at the default settings.

What it looks like

The body stays upright and isn’t stepping (Balancing true, Staggering false), but the pelvis creeps across the floor, the heading swings round and the feet scrub along the ground as if on ice. It doesn’t die away. Measured on the scene 02 rig with no locomotion and no profile, 50 Hz physics, the same Physics settings on both editors (iterations 6 and 1, friction, damping, maximum angular speed 7), over 8 s:

Unity 6000.3.19f1Unity 2022.3.62f3
Pelvis path0.00 m0.42 to 0.62 m
Heading turnednone26° to 67°
Feet scrubbed0.000 m0.5 to 1.2 m
Yaw rate (rms)0.014 rad/s0.26 to 0.44 rad/s

On 2022.3 it was still moving after 28 s.

Why it happens

Each physics step the articulation solver resolves the joints’ drives and the feet’s contacts with the floor in a fixed number of passes (position iterations). With too few, a little error is left over every step, and on 2022.3 it shows up at the feet: they slip on the floor while the legs are aiming them at a fixed spot. Only friction can hold a body in place. The leg drives are internal: they move the feet relative to the hips, but they can’t move the whole body back across the floor. So once the friction isn’t converged, nothing the balancer aims at stops the slide. The balancer keeps a planted foot’s target where it was put down, and lets it follow the sole only once the foot has slipped more than 2 cm. That follow is a consequence of the slip, not its cause (see the latch test below). A body standing on its animation hides the same error behind the pin to the animation.

On Unity 6 the solver resolves this rig well enough at 6 iterations that the feet hold. On 2022.3 it needs about 20. Why the two engines differ is not known. Both 2022.3 and Unity 6 ship PhysX 4.1.2, so this is not a newer PhysX. It could be a change in Unity’s own articulation solver integration. The two projects were checked for every other difference that could explain it, and none was found (next section). The drift fades steadily as the iterations rise (12, 16, 20, 30). That fits a solver that isn’t converging. A wrongly applied force would not fade like that.

What was ruled out (on 2022.3)

TriedResult
Position iterations 12still slides
Position iterations 16still slides after 20 s
Position iterations 20still: 0.06 to 0.08 m of path, 4° to 6°, yaw 0.01 to 0.02 rad/s
Position 30, velocity 8still: 0.02 m
Velocity iterations 4 or 8 aloneno change
Friction 1 or 3 on every colliderno change, if anything worse
Gains.YawDamping 0no change, so this isn’t the yaw-damping shake fixed earlier
Link linear and angular damping 0 (the wizard sets 0.05)still slides: 0.29 to 0.66 m of path, heading 55° to 110°
Every link’s setup compared between the two editors (mass, centre of mass, inertia, drives, limits, colliders, contact offsets, materials) and every Physics setting (solver type PGS on both, friction type, patch friction)the same, apart from float rounding and the pelvis’s inertia rotation about an axis where two of its moments are equal (no physical difference)
Latching each planted foot’s spot in the world (re-planted past 5 cm)still slides: 0.23 to 0.40 m of path, heading 31° to 36°; the feet slipped past the latch 11 to 41 times. No change on Unity 6.
Latching each planted foot’s spot and headingless slide on 2022.3 (0.19 to 0.29 m of path) but a new twist back and forth (yaw 0.5 to 0.7 rad/s). On Unity 6 it breaks a dead-still stance: yaw 0.014 → 0.6 to 0.8 rad/s, 0.11 to 0.15 m of path.

The damping test was run because of a 2022 ArticulationBody damping bug (UUM-32857). Unity’s tracker lists that bug as fixed in 2022.2.22f1, before the 2022.3 branch, and the test agrees it isn’t the cause. Another claimed cause, extra torque from AddRelativeForce (UUM-57137), can’t apply here: the package never calls AddRelativeForce or AddRelativeTorque. The latch runs were single 8 s windows at 3 s and 20 s; the 2022.3 baseline itself varies run to run (0.42 to 0.62 m of path).

The fix

Give the character about 20 position iterations on Unity 2022.3. Either:

#if !UNITY_6000_0_OR_NEWER
character.SetSolverIterations(Mathf.Max(character.Root.solverIterations, 20), character.Root.solverVelocityIterations);
#endif

The fix was measured by setting the iterations on every link. The Project Settings route and SetSolverIterations weren’t timed or re-measured separately.

Not checked yet

Debugging

Troubleshooting

SymptomWhat to check
The character falls over at onceRun the Validator. Usual causes: an Animator left on the character (Fix removes it), a fixed timestep slower than 50 Hz, a body outside 0.6× to 2.5× the reference height (or resized without Scale to Rig), or limbs overlapping (lower Limb thickness in the wizard).
A much larger or smaller character steps oddly or goes over too easilyIts tuning is still set for the reference body. Press Scale to Rig in its inspector, then use the Rig Calibrator if it is still off. See Tuning.
It stands but never walksMarionetteLocomotion needs Idle and Walk clips with root motion; the console says so on start. See Locomotion clips and root motion.
Pink materials in the Demo ScenesThe samples carry a solid colour shader for each of the Built-in, URP and HDRP pipelines, and move their materials to the one your project uses when the sample is imported or the pipeline changes. If they are still pink, run Tools > Despair Physics > Demo Scenes > Switch Materials To Current Pipeline. A custom scriptable pipeline needs materials of your own. The package itself doesn’t render anything.
Compile errors after importing the Demo ScenesThey need the Unity UI package (com.unity.ugui). The Input System package is optional.
Bodies jitter or sink into each otherThe ragdoll layer must collide with itself (the Validator offers the fix), and Physics.simulationMode should be FixedUpdate.
A character moved by script snaps backNever move a live character’s root transform: call Teleport.
A body thrown on purpose (a mine, a cannon) jumps back to where it stood, or stops spinning mid-airThe blow-up guard took the throw for a solver explosion: past MarionetteCharacter.RunawaySpeed (60 m/s of the centre of mass) it stands the body back up where it last was, and past RunawaySpin (60 rad/s, a quarter of the joints) it cuts the spin. Raise them on characters your game throws (the parkour demo uses 1000 and 400), or set float.PositiveInfinity to switch a check off. A non-finite position or velocity always counts. Set them from code; they aren’t saved with the scene.
A downed body never gets up (on a belt, a slope, under falling props)The automatic get-up waits for the body to lie still and is cut short by every knock. Call ForceGetUp() after a while downed.
Other Rigidbodies stutter when a character hits something hardRagdollStepping.Substepped ran that step in substeps, which Unity’s own interpolation skips. See Interpolation.
On Unity 2022.3, a character standing without locomotion slides and turns on the spotThe solver needs about 20 position iterations there (Unity 6 manages with 6). See Unity 2022.3: standing bodies drift.
A Generic rig doesn’t mapOpen Bone for each part in the wizard and pick the bones by hand, or tick Guess from names and check every bone.

Units

Metres, seconds, kilograms, N·s for impulses, radians for joint angles and tilt. These are the same units as Unity physics.

Moving ground

Balance works relative to what the feet stand on: a body on a kinematic platform or vehicle (moved with Rigidbody.MovePosition) is carried by it. Tested standing, without locomotion, on a platform at 0.3 m/s that turns back and forth; a body standing on its own loses its footing above about 0.4 m/s. A body on its animation (with locomotion) has the animation’s path laid on the ground under its feet, so it rides the deck without leaving its animation: tested at 0.6 m/s, within 15 cm of where it stood on the deck. A body getting up on a deck rises with it: the get-up follows the kinematic deck under the pelvis (its speed, its turn and the height of its top). Tested with a forced get-up on a deck moving at 0.8 m/s: the body stood up on the deck, within 0.75 m of where it lay on it.

Look and feel

The play-mode tests come in two kinds. RagdollPlayModeTests check that bodies survive: standing, any timestep, a thousand random hits, pooling, tiers. ReactionFeelTests check how they react, graded both ways: shoves of 40 to 300 N·s from three directions (caught with steps, fought for, or felled), the sample weapons (each landing harder than the last, a shotgun’s pellets as one blast, a burst carrying the body off), a body thrown into another, and, on the animated sample character, feet and hands against the clip, a moving platform, the head after a stagger and a front get-up. Each runs on the bare test skeleton and, when the Demo Scenes sample is imported, on the sample character; the sample cases report as ignored without it. Every test writes its numbers (falls, steps, travel, speed after the hit, peak tilt, steps cut off in the air) to the test output: run them after retuning, and read them as a report.

Known limitations