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.
- Unity 2022.3 LTS or newer, built-in 3D physics (PhysX). Unity Physics and Havok are not supported. Built and tested on Unity 2022.3 LTS and Unity 6.3. On 2022.3, bodies standing on their balance alone need more solver iterations: see Unity 2022.3: standing bodies drift.
- Render-pipeline agnostic: only samples touch rendering.
- No built-in networking. PhysX is not deterministic across machines, so lockstep and rollback are out. Host-authoritative
works: simulate the ragdoll on the host only and send the bone poses (root position and rotation, plus each part’s
rotation) to the clients, which just drive a plain copy of the model. The package has no pose-replication component
yet, so that sync is yours to write.
SetSeedkeeps the body’s random choices reproducible if you do replay a hit.
Folder layout
| Folder | Assembly | What |
|---|---|---|
Runtime/ | DespairPhysics.Runtime | Everything 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.Editor | Setup 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.Samples | Fifteen demo scenes, seven example profiles and their scripts (import from Package Manager). Safe to delete. |
Tests/Editor/, Tests/PlayMode/ | DespairPhysics.Tests.Editor, .PlayMode | Edit-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):
- Two legs, two arms, a torso, a neck and a head. Each leg and each arm has three bones: upper, lower, and hand or foot (thigh, shin, foot; upper arm, forearm, hand).
- A pelvis (hips) at the root of the torso, with a chest bone that the two clavicles hang from, and a neck above it. One to six or more spine bones may sit between the hips and the chest. Fewer than three merge into the chest joint; extra ones ride along unsimulated.
- Each side has a clavicle (shoulder bone) between the chest and the upper arm.
- Upright and bipedal. Digitigrade legs, extra limbs and non-humanoid creatures are out of scope.
- Bones named by a supported preset, or a Humanoid avatar. The wizard finds them from the first of: the Humanoid
avatar; a naming preset (Mixamo, Unreal mannequin, Character Creator CC3/CC4, Daz Genesis 2/3/8/9, VRoid,
Blender Rigify, Blender Auto-Rig Pro, 3ds Max Biped); or, with
UseNameHeuristics, words in the bone names (unreliable, so review the mapping). A Generic rig with no preset is mapped by hand in Bone for each part. 3ds Max Biped maps only with Triangle Pelvis and Triangle Neck on, or through a Humanoid avatar.
The model:
- A humanoid character with a skinned mesh. Colliders are sized from the mesh, falling back to the bones and the character’s height.
- The builder normalises the instance for you: it turns the skeleton to face +Z, poses an A-pose into a T-pose, and moves the soles onto the origin. You do not need to fix those in the source.
- Size: 0.6× to 2.5× the 1.8 m reference (1.1 m to 4.5 m). Mass defaults to 94 kg scaled by (height / 1.8 m)³. Bodies outside the range are flagged by the Validator; a body resized by hand needs Scale to Rig.
The animation:
MarionetteLocomotiontakes Idle and Walk clips; it needs a Walk to walk. Run and the get-up clips are optional (a missing get-up uses the package’s own). Without locomotion the balancer holds the body up on its own.- Clips are all Generic or all Humanoid, matching the avatar. A Humanoid clip does nothing on a Generic avatar, and the reverse.
- A walk that moves must carry root motion: on a Generic rig, set Root node (Rig tab) to the pelvis. A walk that stays in place
needs
InPlaceWalkSpeedset instead. See Locomotion clips and root motion. - Loop Time on for Idle and Walk clips.
The project:
- Unity 2022.3 LTS or newer, built-in 3D physics (PhysX). Unity Physics and Havok are not supported.
- Fixed timestep 50 Hz (0.02) or faster; the Validator flags anything slower.
Quickstart
-
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:
- 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).
- Bones: what the mapper found. Problems are listed first; open Bone for each part to fix them.
- 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.
- Animation: the model the hidden animation skeleton is made from, and locomotion clips.
- 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.
-
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.
-
Check every ragdoll in the open scenes with Tools > Despair Physics > Validator. The
ActiveRagdollinspector 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.
| Scene | Shows | Read |
|---|---|---|
| 01 Quickstart | One character: push it, kill it, watch the events. | ClickToPush, RagdollEventLog |
| 02 Build a Ragdoll | The Setup Wizard and the Validator on a raw model, with no code. | BuildARagdollGuide |
| 03 Hits | A 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 Handoff | Who 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 Terrain | Locomotion over stairs, a slope, a ledge and a moving platform. | TerrainWalker, PlatformMover |
| 06 Reactions | Nine 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 Profiles | The seven example profiles and your own, side by side, taking the same five hits. | HitComparison, ProfileShowcase |
| 08 Dials | The 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 Scaling | One character at 1x, 2x and 0.6x, untouched, scaled to the rig and calibrated, shoved alike. | HitComparison |
| 10 Locomotion Options | The same patrol and shove with clips, a Mecanim controller and a locomotion of your own. | PatrolLocomotion, LocomotionDemo |
| 11 Debug Tools | The debug view, the recorder, the incident log and interpolation on one shoved character. | DebugToolsDemo |
| 12 Benchmark | Add characters until your frame budget runs out; what each one costs. | RagdollBenchmark |
| 13 Mobile | The benchmark with cheaper physics settings and the Mobile profile, for phones. | MobileTuningDemo |
| 14 Playground | A 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 Interactions | Loose 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
- Two layers.
ActiveRagdoll(withActiveRagdollProfileandActiveRagdollTuning) is the gameplay API: send it hits and commands, read its state, listen to its events. TheMarionette*types underneath (MarionetteCharacter,MarionetteAnimator,MarionetteLocomotion,MarionettePart) are the simulation;ActiveRagdoll.Characterreaches them when you need to. - A part is one rigid body of the 20-part rig (an articulation link with a
MarionettePart, indexed byRigDefinition). Its effector is the muscle that drives its joint. - A behaviour (
MarionetteBehaviour, internal) sets effector targets every physics step:DynamicBalancersteps to catch the body,StayUprightholds the trunk up,BodyBalanceswings the arms out, and so on. - The animation skeleton is a hidden, animated copy of the character’s model that the body follows.
In code it is called the ghost (
MarionetteAnimator.Ghost). - A stagger is losing balance on the way to a fall; a stumble is a runner taking a hit and running on.
- A reaction (
ReactionModule) is one switchable piece of how a character answers a hit, saved in its tuning or profile.
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.
| Group | Types |
|---|---|
| Talking to a character | ActiveRagdoll (and its Events), IActiveRagdoll, RagdollState, RagdollHand, GripKind, RagdollHit, RagdollHitRecord, RagdollBalance, IRagdollBody, RegionPose (from PoseRegion, see Tuning) |
| Driving the body from gameplay | BalanceSteering (on MarionetteCharacter.Steering, see Walking from gameplay), and on ActiveRagdoll: ForceGetUp, GetUpForced; on MarionetteCharacter: RunawaySpeed, RunawaySpin |
| Rules | ActiveRagdollTuning, 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) |
| Components | MarionetteCharacter, MarionetteAnimator, MarionetteLocomotion (and LocomotionState), MarionettePart, MarionetteInterpolation |
| Your own locomotion | ILocomotion, LocomotionHost, GetUpResult, BodyMask (see Extending locomotion) |
| Your own behaviours | RagdollBehaviour, and on MarionetteCharacter: AddBehaviour, StartBehaviour, StopBehaviour, RemoveBehaviour, BehaviourReported (see Your own behaviours) |
| Body set-up | On MarionetteCharacter: GroundLayers, PhysicsScene, JointLimits, SetJointRange, GetJointRange, InertiaGains, ApplyInertiaGains, RefreshMasses; on MarionetteAnimator: GhostBones, CopyFingers, PauseWhileUnused, Paused, PoseChanged |
| Stepping | RagdollSimulation (Stepping, AutoStep, MaxTravelPerSubstep, MaxSubsteps, ImpactLayers, LastSubsteps, SubsteppedSteps, SubstepStarting, InterpolationAlpha, Step, Simulate, AfterSimulation), RagdollStepping, RagdollSimulationSettings (see Stepping physics yourself) |
| Where the pose comes from | IPoseSource, 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 aids | RagdollLod, RagdollTier, RagdollTierSettings, RagdollLodMode, RagdollLodSettings, RagdollStats, RigDefinition (part indices and masses, ParentOf, MaskOf, RadiusOf) |
| Debugging | MarionetteDebugView, MarionetteRecorder, MarionetteIncidents |
| Editor scripting | RigMapper, 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
-
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
mixamorigprefix), 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.
-
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. SetTotalMass, or leave 0 to scale 94 kg by (height / 1.8 m)³.RegionMassmultiplies regions, andVolumeMassWeightshares mass by collider volume instead of the anatomical table (for cartoony proportions). Muscle strength scales with mass × height. Pass a list asSettings.Reportto see what was done. Finally it adds an articulation link, collider andMarionetteParton each rig bone, thenMarionetteCharacter,MarionetteAnimatorandActiveRagdoll. -
Optionally, add
MarionetteLocomotionand assign its clips (Idle, Walk, Run, get-ups). Without it, the balancer holds the body up on its own.MarionetteLocomotionis 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.
-
Set Root node on the Rig tab (Animation Type Generic) to the bone that travels, normally the pelvis. The field only appears once Avatar Definition is set to Create From This Model (press Apply if you just changed it). Left at
None, the clip has no travel and the character stands in place. Leave the Root Motion Node on the Animation tab’s Motion foldout alone: with the Rig tab’s Root node unset, setting it did not give a test model’s walk any root motion. -
Leave Root Transform Position (XZ) > Bake Into Pose off on the Walk and Run clips. It is off by default. Ticking it moves the travel into the pose, the clip becomes an in-place clip, and the console says so. The other Root Transform options can stay at their defaults too.
-
Turn on Loop Time (and Loop Pose) for the Idle and Walk clips, or a walk plays once and stops. The per-clip settings are in HowToCreateSampleCharacterInBlender.md.
-
Idle and the get-up clips need nothing. If an Idle clip drifts across the floor, tick Bake Into Pose on its Position (XZ) to hold it still.
-
If the clip’s root rotation is keyframed (the clip itself turns), tick Root Transform Rotation > Bake Into Pose on it too, for the reason given under Humanoid clips below.
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.
| Clip | Root Transform Rotation | Root Transform Position (Y) | Root Transform Position (XZ) |
|---|---|---|---|
| Walk, Run (moving) | Bake Into Pose on, Based Upon Original | Bake Into Pose off, Based Upon Original | Bake Into Pose off, Based Upon Original (this is the travel) |
| Idle | on, Original | off, Original | off, Original |
| Get-up (both) | on, Original | on, Original | on, 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.
- The value is used only for a clip that has no root motion of its own. A clip with root motion keeps it, so the fields can stay set when you swap clips.
- It is read when the character starts. Changing it in play mode has no effect until the next start.
- The travel is along the character’s forward (+Z); turning to the goal still works.
- From code,
MarionetteAnimator.SetInPlaceSpeed(clip, speed)does the same for any clip you play yourself, andClipVelocity(clip)then reports it.
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):
- Pathfinding. Feed
MoveTothe corners of a NavMesh path one at a time, withbrake: falsefor the corners in between so the body doesn’t slow at each. The body already keeps its path on the NavMesh where there is one. - Avoiding other characters, detecting obstacles ahead. Steering: offset the point you pass to
MoveTo.MarionetteCharacter.Alllists every live character. - Whatever moves the body, hand it to physics through
Disturb(); the locomotion takes it back once it stands still.
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 path | TargetYaw, MaxTurnRate, PathSpeedScale, PathVelocity, RootYaw, Nudge, Anchor, PinRegion, FreeJointPull, IsPinned, IsFollowing |
| What pushed the body | PinKick, GroundDrop, ChestError, NavMeshBlocked, TouchingObstacle, TouchingStep, ObstacleAway |
| Handing the body over | Follow(blendTime), ReleaseToBalancer(), StopFollowing(), PoseFromAnimation(), BalancerActive, BalancerStableTime, IsUpright |
| Getting up | StartGetUp(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 it | GetUpFinished, GetUpFailed, BalanceLost |
| Hit tuning from the profile | StumbleSpeed, 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):
- The clip mixer (
MarionetteAnimator.ClipMixer, the default) crossfades clips and a locomotion blend:Play,GetOrCreate,CreateMixerPolar. It is deliberately basic: no masks, additive or IK layers. - Mecanim, with no code. Put an Animator Controller in
MarionetteAnimator.Controller(orSetSource(new MecanimPoseSource(controller))): state machines, blend trees, layers and avatar masks work as in any Animator, and its root motion carries the body. Add anAnimatorParameterDriverto writeSpeed,Running,StateandGettingUpinto the controller’s parameters.MarionetteLocomotionthen takes only the gait speeds from its clips (Walk, and Run if any; Idle isn’t needed): it steers, the controller draws. Put the layer that moves the hips first in the controller, and use Generic clips (below). - Your own source, for masks, additive layers or another animation library: implement
IPoseSource(CreatePlayable,Advance,GetPlaying) andSetSourceit after the animator has started. A source may wrap another:new LayeredSource(animator.ClipMixer)puts your masked layers over the clip mixer. Report fromGetPlayingthe clips of the layer that moves the hips and root, with their weights; the package uses them only to correct the root motion’s frame, the in-place speed and how much of the pose is animated. Get-up clips play on a layer the package owns above your source, so you never see them. Animancer fits this shape (itsAnimancerGraphcan be created in an existingPlayableGraph), but the package ships no Animancer code and the combination is untested.
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.
- Unity (the default): every character steps from
FixedUpdate, just before Unity’s simulation. - Substepped: the same, except for a step in which a fast body is about to hit something. The package runs that step
itself, as several shorter simulations, each with a step of every character, and hands physics back to Unity for the
next (
Physics.simulationModeis Script only meanwhile; Unity’s own simulation of that step is skipped). At 50 Hz a body that lands or hits a wall at 20 m/s or more is otherwise stopped within one step: its upper body drives the spine and neck far past their limits, and the solver blows up. A step is split so no body travels more thanMaxTravelPerSubstep(0.2 m) in one, up toMaxSubsteps(4), and only where something onImpactLayers(other than the body’s own limbs) is within reach: a body in free flight costs nothing.LastSubstepsandSubsteppedStepssay how often it happens. Forces added withAddForceact on one simulation: add the ones yourFixedUpdateadds for the whole step (a wind, a thruster) again fromSubstepStarting. The characters’ own forces are added again by themselves; impulses and velocity changes must not be. Kinematic bodies moved withMovePositionreach their target in the first substep. It needs every character in the default physics scene; with any elsewhere, steps stay whole. Trade-off: Unity’sRigidbodyinterpolation doesn’t run for a step simulated in substeps. Characters are not affected (MarionetteInterpolationdraws them between steps however physics is stepped), but other interpolated Rigidbodies (props, vehicles, a camera target) are drawn unevenly through that step: in the tests, a box gliding at 5 m/s with every step in substeps moved unevenly on more than 30% of frames, against none with whole steps. Substeps only come in the steps around an impact, so it shows as a short hitch on what is in view then. The fix is under Interpolation. - Manual: for
Physics.simulationModeset to Script (rollback, prediction, several simulations per frame, a local physics scene). Nothing steps until you callRagdollSimulation.Simulate(dt)(orStep(dt)before your ownPhysics.SimulateandAfterSimulation()after it).AutoStep = falseis the same.
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
| Call | Effect |
|---|---|
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.
| Event | Raised when |
|---|---|
StateChanged(from, to) | State changes. |
Struck(hit) | A hit reached the body. |
LostBalance | A living body can no longer catch itself and staggers. |
Fallen | A living body went down. |
Recovered | A stagger caught itself, or the body got up. |
Revived | Revive() brought a dying or dead body back. |
Died | The body entered Dead. |
Settled | A corpse came to rest (after SettleTime) and may sleep. |
GetUpStarted | A 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
- Holding. While
Active, the body stays on the balancer: it doesn’t give up for taking many steps or balancing long, and it still falls when the trunk tips past saving. A body withMarionetteLocomotiongoes back to its animation after a get-up: callLocomotion.Stop()andDisturb()again if the game wants it. - Planned steps. With
PlanSteps, steps come on a rhythm (StepTime,DoubleSupport) and are placed by capture-point control (CaptureTimeScale,MaxStepLength,MaxLead,MinStride,StanceWidth); each foot lands turned towardFacing, at mostMaxTurnPerStepa step.FootGap(below 0: the balancer’s own) is the least sideways distance from the other foot’s line; smaller lets the inside foot of a turn help redirect the body.PlannedStepscounts them. - Pace.
HoldPace(on): the balance layer damps the body towardVelocityinstead of braking it back over its feet, so each step doesn’t have to win back the speed the last one lost.LeanPerSpeed(0.05 rad per m/s, at mostMaxLean) leans the trunk into the walk. The steps alone don’t hold a pace: push the trunk toward it from yourFixedUpdate, as below.PaceCorrection(0) moves each step by the body’s speed error instead; on the test rig 0.25 made the walk fall at 1.2 m/s without a push, so treat it as something to try on your rig, not a fix. - Uneven ground. Planned steps look
TerrainLookahead(2 m) ahead alongVelocity. Over stairs or kerbs the walk slows toStairPace(0.55) of it, up or down a slope of 27° or more toSlopePace(0.75), easing between; with a step up withinStepUpReach(0.5 m) and no foot on the level above it yet, to at mostStepUpSpeed(0.5 m/s). The result isTerrainPace, andPacedVelocityisVelocitytimes it: push towardPacedVelocity, notVelocity. Going up,ClimbAssist(0.5 of the body’s weight at most) lifts the pelvis to standing height over the leading foot’s tread and pulls a trunk left behind its feet over them. Over stairs and steep slopes, up or down,TerrainUpright(0.5) stands a pitched trunk back up (going down too: in the tests, without it the trunk tilted up to 20° on the way down against 12°). Set any of them to 0 to switch it off, orStairSteppingoff for all of it (below). Down a flight of stairs none of this applies unlessStairSteppingDownis on (below): the walk keeps its pace andTerrainUprightstays off. - Landings.
CatchLandings(on): once both feet have been off the ground forLandingDelay(0.08 s), a foot reaches for where the capture point will be at touchdown (at mostLandingReach, 0.85 leg lengths, from under the hips), and the balance isn’t given up on while the body flies, nor forLandingGrace(0.35 s) after it lands.AirborneandSinceLandingread it. A hop that barely clears the floor doesn’t count: the feet sense ground about 20 cm below the soles.
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
-
How a character behaves is decided by its tuning alone. There are no modes or presets: a character runs exactly the numbers it holds and the reactions it has switched on. A new tuning starts with the package’s defaults (hard-hitting, quick to react, every reaction on); a grounded, weightier character is other numbers, such as each behaviour’s own defaults in its
ResetParams, and fewer reactions switched on. -
Reactions (
ReactionModule, listed inActiveRagdollTuning.Modules) are the things a character does in answer to being hit, losing its balance or dying, each a foldout in the inspector with its own checkbox and its own numbers:WoundReach(a hand goes to the wound, and the head glances at it),LegHit(injury, buckle, stumble step, collapse on repeat hits, and standing on the good leg with the trunk curled over the wound),ArmsOut(arms swing out for balance, windmill, brace),Stagger(tiring steps before the fall),HeadHold,CarriedDeath,FreeArm,WallGrip,GracefulFall,DeathShove,KeepFeet,CatchEveryStep,HandsOut,Tumble,HighFall,FallGrip(a falling body catches an edge and hangs from it, kicking, until its hands give out),GetUpHit(a hit on a body that is getting up drops it back down),Writhe(a body knocked down alive is hurt on the floor: its pose follows how it lies, on its back, front or a side; a hand holds the wound; it rolls onto a side and props itself on an elbow now and then; it tires as it goes; off, it lies as it landed) andGetUp(a downed body gets up by itself; off, it stays down until the game callsGetUp(), for a kind of character that never rises on its own).WallGriptells a flat surface from an edge: a palm on a wall can only lean, low beside the torso with the forearm running down to it, while an edge is held all round andEdgeGriptimes as hard. The balancer’s own behaviours are modules too:SlipStep,CloseStance,StepRhythm,LandingGive,StepPlanningandCreepBrake. A reaction that is switched off never happens, whatever its numbers say (withStaggeroff, losing the balance is going down; withArmsOutoff, the arms stay on the animation). Each module also writes its numbers into the behaviour that carries them out, soWoundReach.HoldTimeorStagger.LeanEndare reachable from the inspector without touching the behaviour. -
Tuning,Profile,ApplyTuning(),UseOwnTuning()and the dial calls (GetDial,SetDial,ResetDials) are onIActiveRagdoll, so a difficulty setting needs no cast.ScaleToRigstays onActiveRagdoll: it is a setup call. -
To switch a reaction at runtime, set
character.Tuning.Reaction(ReactionKind.WallGrip).Enabled = false. It takes effect at the next hit or stagger;Tuning.Moduleslists them all, each with a readableTitle. A reaction’s numbers are public too, by type:character.Tuning.Reaction<WallGripModule>().Chance = 0.2f(a difficulty setting, say). What a reaction decides when it happens (its switch, chances, ranges and times) is read then, so a change takes effect at once. For what a module copies into a behaviour (the arms-out switch, a stagger’s numbers) callActiveRagdoll.ApplyTuning()after the change; standing back up does it too. A profile is shared, so callUseOwnTuning()first to change one character. -
To add a reaction inside the package, derive a
[Serializable]class fromReactionModule, give it public fields (they are the inspector, withTooltip,RangeandMinas usual), overrideValidateand, if a behaviour carries the numbers,Apply. Declare it as a[SerializeField] internalfield ofActiveRagdollTuning, list it inModulesand add aReactionKindfor it; the inspector, profiles,Clone,CopyFromand validation pick it up from there. A module is shared by every character using a profile, so it holds numbers and no per-character state. -
Custom reactions are your game’s own, kept in the tuning with the package’s, so a profile holds everything that decides how a character reacts. Derive a
[Serializable]class fromCustomReaction, give it public or[SerializeField]fields for its numbers, and override the hooks you need:OnBeginandOnEnd,OnUpdateandOnFixedUpdate,OnRestarted, and one for each event (OnStruck,OnStateChanged,OnLostBalance,OnFallen,OnRecovered,OnDied,OnRevived,OnSettled,OnGetUpStarted,OnLanded,OnGripped,OnGripReleased). Each hook is told whichActiveRagdollit is for, since one reaction in a profile serves every character that shares it: keep what it does to one character inStateOf<T>(ragdoll), which is that character’s own and is dropped when the reaction ends for it. Add it in the inspector’s Custom Reactions section (Add Reaction lists every such class in the project) or from code withtuning.AddReaction<T>()andRemoveReaction; it has a checkbox like the others,Tuning.Reaction<T>()finds it, and it is saved, copied and validated with the profile. A reaction begins for a character once the character has started, and ends when it is switched off, removed, the profile changes or the character is disabled or destroyed; edits reach running characters by their next step. A hook that throws is logged and the other reactions still run.ActiveRagdoll.RunningCustomReactionslists those running for a character.[Serializable] public sealed class FlinchOnHitReaction : CustomReaction { [Range(0f, 1f)] public float Chance = 0.5f; sealed class Memory { public int Hits; } protected override void OnStruck(ActiveRagdoll ragdoll, RagdollHit hit) { if (ragdoll.State != RagdollState.Active || UnityEngine.Random.value > Chance) return; StateOf<Memory>(ragdoll).Hits++; ragdoll.Disturb(); } } -
Posing a region. A custom reaction can hold part of the body in a posture of its own, kept by the joints under hits rather than played as animation, while balance, stagger and hits go on with the rest. Examples: arms up to shield the head, a limp held on one leg, a lean into cover. Call
ragdoll.PoseRegion(this, region)with one or moreBodyMaskgroups (Arms,LeftLeg,Spine…). It returns aRegionPosewhose calls chain:SetTarget(part, degrees)for one joint (aRigDefinitionpart index; x bends, y swings to the side, z twists, from the rest T pose, the same numbers for both sides),HoldCurrent()to keep the region where it is,SetStiffness(stiffness, dampingRatio)(a natural frequency, 9 the body’s resting tone, 0 limp) andSetWeightto blend the pose with what balance asks. A joint you give nothing keeps the target and stiffness the body already drives.ReleaseRegion(this, region)orRegionPose.Release()lets go.A pose is held until it is released, so set it once, from
OnBeginor an event. It is let go, not fought: when the reaction ends, the body loses its balance, falls, dies or is stood back up. Pose again fromOnRecovered. While the body is staggering, down or getting up,PoseRegionhands back a pose that holds nothing (IsHeldis false). Only a reaction running for that character may pose it: any other call throws. A hit still loosens posed joints, and injuries and a dying body’s strength weaken them. The pose is blended into the joint drives after the package’s behaviours have written their targets for the step. While the body plays as animation only it has no effect, and it doesn’t wake the body.[Serializable] public sealed class ShieldHeadReaction : CustomReaction { public float Stiffness = 16f; protected override void OnBegin(ActiveRagdoll ragdoll) => Shield(ragdoll); protected override void OnRecovered(ActiveRagdoll ragdoll) => Shield(ragdoll); // An upper arm swung across the front and twisted turns the elbow's bend upward: the forearm stands in front of the face. void Shield(ActiveRagdoll ragdoll) => ragdoll.PoseRegion(this, BodyMask.Arms) .SetTarget(RigDefinition.UpperArmL, new Vector3(110f, 65f, 75f)) .SetTarget(RigDefinition.UpperArmR, new Vector3(110f, 65f, 75f)) .SetTarget(RigDefinition.ForearmL, new Vector3(115f, 0f, 0f)) .SetTarget(RigDefinition.ForearmR, new Vector3(115f, 0f, 0f)) .SetStiffness(Stiffness); } -
A component next to the
ActiveRagdollstill works for behaviour that belongs to one character only: it listens to the same events (Struck,LostBalance,Fallen,Landed…) and usesHandFree,LookAt,Aimor the body underneath (IRagdollBody: parts, centre of mass, velocity). Its own checkbox switches it. The 06 Reactions scene shows one (RaiseArmWhenHit, which uses the package’s internal arm pose, so it is a pattern to follow, not code to copy as it stands). -
The
ActiveRagdollinspector holds the reaction rules (ActiveRagdollTuning): how hard hits land and how fast the body answers (Feel, the plain numbers written intoShot,StayUprightand the balancer), the reactions above, dying, downed and get-up timing. -
What a hit does, and how the body steps, are reactions too, each with a checkbox: how a hit lands (
LimbCarry,SustainedFire,BigHit,PushCap,RapidSnap,BarrageHold), what it does to the body (Unsnap,NeckWhip,GutFold,BackArch,ArmFlinch,TorsoTwist,HitLean,HitWeakness) and the stepping styles (BrakingSteps,FootRoll,Stride,Stumble, plusStepPlanning’sJumpDistance). Off, the feature is neutral in the shot or the balancer. What is left inFeelis plain numbers with no off state: impulse scales and randomness, the snap, the step timing, reach and height. Profiles and components saved before these moved out ofFeelare migrated when they load (a feature saved as 0 comes in switched off);ActiveRagdollProfile.CurrentVersionis 3. -
Only scripted events topple it.
Feel.IgnorePropImpacts(Physical impacts in the inspector, saved in profiles) stops loose props (balls, crates, debris) from starting a hit reaction: they still push the body through physics, but never stagger or drop it by themselves.Hit,KnockDown,KillandDisturbcalls, and bumps from other characters (controlled by theKnockreaction), work as before. A hard enough push can still unbalance the body on its own; raiseTuning.Balance(BalanceLimits) or the Toughness dial to make that rarer, or switch theStaggerreaction off to make losing balance mean going straight down. From code:character.Tuning.Feel.IgnorePropImpacts = true(callUseOwnTuning()first to change one character, thenApplyTuning()orResetToStanding()). -
Randomness is part of the tuning, so a profile can be steady or loose. In
Feel:ImpulseRandomness,DirectionJitter(how each hit lands) andBigHit.ChanceandPushCap.Randomness,SnapRandomness(how far a snap strays from the hit) andAggressionRange(each stagger’s temperament). In the reactions:ArmsOut.Variance(how much the arms’ swing differs from one stagger to the next),WoundReach.HoldVariance(how long a hand holds a wound), the chances and ranges (GetUpDelay,WallGrip.Chance,DyingTimeand so on) and the relative odds of what a free arm does (FreeArm.RaisedtoFreeArm.Zombie) and of how a standing death goes down (GracefulFall.KneestoGracefulFall.Spin), and how a held head shot arranges the hands (HeadHold.BothOnHeadtoBothFlail). A spread at 0, or a range at 1 to 1, makes that part repeat exactly. Still chosen in code: which hand or side is picked, and the starting phase of the arms’ sway. All of it is drawn from Unity’s globalRandomuntil you callSetSeed(seed)on the character: then it has a stream of its own that nothing else draws from, so two bodies given the same seed and the same hits make the same choices, whatever the rest of the game rolls (for replays and networking;ClearSeed()goes back). The package never reseeds the global stream. -
Where a round lands: an arm or the head is a few kilograms on a joint, the trunk forty: the same push flings one and barely moves the other.
Feel.ArmScale,HeadScale,LegScaleandTrunkScalescale the push by region, andLimbCarrypasses a share of an arm, head or leg hit through the joint into the trunk, so the body takes the hit instead of the limb being flung.HeadSnapMultis the head’s whip on a head shot. A hit arm keeps some tone (Feel.ArmLooseness) and flinches, the elbow folding and the upper arm pulling in (ArmFlinch.Flinch,Time), instead of swinging on the shoulder like a stick. -
A hit leg hands its load to the good one (
LegHit.WeightShift): the good leg stays straight and the body moves over it, the hurt knee stays bent with the foot resting on the floor (KneeBend), and the trunk curls over toward the wound (Hunch). All three ease off as the leg recovers (InjuryRecovery). -
Repeat leg hits: those inside
KneecapWindowseconds add up.HitsToCollapseof them (2 by default) knock the body down;SameLegOnlycounts only hits on one leg;Collapseoff lets a leg be shot again and again with the body only limping;RepeatWeakeningleaves each further hit on a leg weaker still (strength × (1 - it) per repeat). -
The balancer’s behaviours each have a switch and numbers like any reaction:
SlipStep(a stance foot sliding with the body steps instead of skating),CloseStance(the feet come back together once the body has stopped),StepRhythm(the feet take turns),LandingGive(the knee gives as a foot lands),StepPlanning(a step is aimed where the body will be at touchdown and re-planned in flight; off, the jump distance is ignored too) andCreepBrake(a body creeping along is braked to a stop). Off, the behaviour is off in the balancer, whatever its numbers say. -
Profiles: save a character’s rules as an asset and share them. Click Save to profile… in the inspector (it works in Play mode, where changes to the character are lost on exit), or use Assets > Create > Despair Physics > Ragdoll Profile. Assign the asset to Profile on any number of characters. A profile is shared: editing it, or
ActiveRagdoll.Tuningwhile a profile is assigned, changes every character that uses it. Use own copy (ActiveRagdoll.UseOwnTuning()) copies the values into the character and stops sharing. Assigning a profile to a character that is running applies it at once. A profile cannot tell the characters that share it, so a change made to the profile itself reaches them as follows: what a reaction decides when it happens (switches, chances, ranges) is read then, and what is copied into a behaviour (the feel, the stagger’s numbers) waits forApplyTuning()on each character or its nextResetToStanding. In Play mode the inspectors do that for you: an edit to a character’s tuning, its profile slot or a profile asset reaches every running character that uses it at once. -
Dials: a profile’s inspector opens with seven plain-language sliders, so a character can be shaped without learning the numbers:
Weight,Toughness,Coordination,Injury,Drama,RecoveryandVariability. Each dial moves a group of the numbers below it, so the character still runs exactly the numbers the profile holds. Start from the defaults or an example profile and move a dial or two. The ends of each dial were set by measurement on the sample rig (a chest shove from behind at rising strengths, each dial at nine positions), so a dial answers evenly along its travel; on any other starting point the same ratios apply. On that rig the defaults go over from about 100 N·s, and one dial alone moves that as follows:Dial -1 -0.5 +0.5 +1 What else it shows Weight59 77 153 189 An 80 N·s shove throws the body 3 m at -1 and 0.3 m at +1; steps go from quick and long to slow and short. Toughness59 84 115 141 A push under 50 N·s looks the same at every position. Dying takes 1 s at -1 and 2.4 s at +1. Coordination69 94 96 98 A 25 N·s push takes 5 steps and 3.2 s to settle at -1, 2 steps and 0.5 s at 0, 1.6 steps and 0.25 s at +1. Injury(0 to 1)83 58 A hit leg bends to 50 degrees at 1 (22 at 0), and getting up takes 2.4 s longer. Drama173 135 84 71 The arms swing 100 degrees on an 80 N·s shove at -1 and 290 at +1; a head shot drops the body at once at -1. Recovery103 101 96 100 Getting up from a knock-down takes 7.8 s at -1, 5.6 s at 0 and about 5 s at +1, which is as quick as it gets. Variability113 110 99 108 The lean of like shoves spreads by 4.5 degrees at -1 and 7.9 at +1. Numbers within about 8 N·s of each other are the same: where a hit lands in the idle animation moves a single shove’s fall point by more than that. The dials reach the reactions too: their numbers, and past half way
Injuryswitches offCatchEveryStepandKeepFeet, andDramatowards grounded also switches offHeadHold,CatchEveryStepandKeepFeet. A dial never switches a reaction on.Toughnessis whether the body keeps its feet once its balance is in question: towards -1 it starts to stagger early and the stagger ends in a fall sooner; towards +1 it braces against the hit at the hips (Feel.CounterImpulseToHips) and its limits open. It leaves a light push looking the same, which is what sets it apart fromWeight. No single balance limit shifts when a body goes over, because any one of them can put it down, and no balance limit at all raises it: past about 110 N·s the fall is physical. The dials add up, but only a little past the furthest any one of them goes: past it they ease toward that limit rather than stopping dead, so a third dial pushing the same way still shows. Back at 0, a dial restores what it moved. A number changed by hand after a dial wrote it stays as it is, and the inspector counts those; Reset Dials puts the dials and the rest of their numbers back. Saving new numbers over a profile (ActiveRagdollProfile.Save) makes them the new starting point. From code useActiveRagdollProfile.SetDial,GetDialandResetDials, or the same three onActiveRagdoll, which also work on a character that has no profile (it keeps its own dial positions, shown in its inspector, andUseOwnTuning()takes the profile’s along). Moving a profile’s dial reaches a character as any change to a profile does (see above);ActiveRagdoll.SetDialapplies it to that character at once. -
Fitting a tuning to a body: the numbers are set for the reference body (1.8 m, 94 kg). The character’s inspector shows what the tuning is set for against the body it is on, and the validator warns when the two are clearly apart. Scale to Rig, or the validator’s Fix, sets the numbers for this body in one step: lengths go by its size, times and speeds by the root of its size, and forces by its mass, so it moves like the reference under the same gravity. It also sets
StrengthScaleto mass × height, which the wizard only does at build: scaling a character’s transform doesn’t change it, nor its mass, so a character scaled by hand needs this. Press it again after resizing the body; it goes from where the numbers stand, so pressing twice changes nothing, and dials keep working. On a shared profile it changes every character using it. It leaves the muscle stiffness numbers alone (those go byStrengthScale), the times that are a matter of taste, such as how long a death plays out, and how hard weapons hit: the same round moves a giant less. A body within 2% of the reference counts as the reference. From code:ActiveRagdollTuning.ScaleToRigandActiveRagdollProfile.ScaleToRig, with height and mass as shares of the reference. -
Rig Calibrator (Tools > Despair Physics > Rig Calibrator, or Calibrate… in the inspector) goes further, for a body that scaling alone doesn’t settle, usually a very large one. It enters Play mode with only that character and a floor, scales the tuning to the rig, then shoves the body from behind and tunes five groups of numbers (step size, step time, trunk, balance force and hit strength) until it answers like the reference: where it falls, how far it leans and travels, how long and how quick its steps are. It leaves Play mode by itself, and nothing changes until you press Apply or Save as Profile. A run measures up to 80 tunings, about 170 s of game time each, so some 4 minutes for 40 at 30× on a reference body. Speed sets how fast it runs. Falls and steps read the same at any speed the machine keeps up with; a frame covers so much game time at 30× that death and get-up times do not, so it doesn’t measure them. It aims at the reference on the package defaults, so calibrate first and shape the character with the dials afterwards. Two runs of one character differ by about 3 to 5%, more without an idle clip. A gain that doesn’t hold up when measured again is dropped, so the result may be the scaling alone. It may raise or lower Hit strength, which changes how hard every weapon lands on this character.
-
The 07 Profiles scene in the Demo Scenes sample shows this at work: the Default, Heavy, Light, Drunk, Injured, Realistic, Cinematic and Mobile presets (and a lane for your own profile) take the same five hits, with a grid of who stood. The presets are made with the dials alone, so each opens in the inspector with its dials moved and no number set by hand: Heavy is
Weight1 andVariability-0.8; Light isWeight-0.7 andVariability0.4; Drunk isCoordination-1,Variability1,Recovery-0.8 andWeight-0.3; Injured isInjury1; Realistic isDrama-1,Weight0.6,Variability-1 andRecovery-0.6; Cinematic isDrama1,Recovery0.3 andToughness0.3. Mobile is about cost, not character: a few reactions switched off and no dial. Start from one, move a dial or a number, hit it again, and compare. The 08 Dials scene does it with the seven dials instead, and 09 Rig Scaling shows what Scale to Rig changes in a body of another size. -
The 06 Reactions scene shows the reactions one by one: nine bays, each with the same character twice, the left with the reaction on and the right with it switched off (
Tuning.Reaction(ReactionKind.X).Enabled = false), both on one steady profile with the dice fixed, so the reaction is the only difference. A camera tour hits one pair at a time; Space hits again, P pauses, Left and Right change bay and S slows time to a quarter. -
Profiles carry a format version (
ActiveRagdollProfile.CurrentVersion). An asset saved by an older release is migrated when it loads; one saved by a newer release logs a warning. -
Advanced:
ActiveRagdoll.Characteris the body underneath (MarionetteCharacter): parts, centre of mass, tier,Teleport,Restart. The behaviours that drive it are internal. -
Looking stiff? These knobs carry most of the “human touch”, and all are in a profile:
FootRoll.ToeOff,HeelOffandAnkleStiffness(foot roll and how firmly the ankle holds),HandsOut.ReachDelay,AbsorbBendandAbsorbStiffness(how the hands meet the floor),ArmsOut.WindmillandBraceReach(stagger arms). UncheckingFootRoll(orToeOff,HeelOff,WindmillandBraceReachat 0, andAnkleStiffnessat 1) turns the matching motion off.Feel.StanceKneeis how bent the knees stay while the body balances on its steps: near straight by default, as a person stands; raise it for tired or drunk legs that sink into the knees. -
Bodies bumping into bodies:
MarionetteCharacter.KnockSpeed(how fast a part must close on another body to knock it, rather than be leaned on like a wall),KnockTransferandKnockRecoil. These three belong to the body, not to the profile, so they are set on theMarionetteCharacter(ActiveRagdoll.Character); theKnockreaction in the profile decides which states may knock and be knocked, on top of them. -
Who can knock whom: the
Knockreaction (Body contact in the inspector) says which states of a body may knock other bodies about (CanKnock) and which may be knocked (CanBeKnocked). States are the flagsKnockStates:Walking(animated, or standing with no locomotion),Stumbling,Recovering(the balancer has it and it has not lost its balance),Staggering,Dying,Downed(falling or lying),GettingUpandDead. By default a dead body or one getting up does not knock (a corpse sliding into a pedestrian is an obstacle, leaned on or walked round), and every state can be knocked. It only vetoes: the speed rule above still applies. Switched off, a body neither knocks nor is knocked. Read a body’s state withActiveRagdoll.KnockState; set the masks from code withActiveRagdoll.SetKnockStates(canKnock, canBeKnocked), which writes to the tuning in use (a profile is shared: callUseOwnTuning()first to change one character). -
The balancer’s core gains are in the profile as
Tuning.Gains(BalanceGains): leg stiffness and damping ratio, hip height offset, stance half width, support margin, hold gain and lift, the swing-foot helper; the pelvis and chest stiffness and damping,TrunkGainMin(how firm the trunk stays under a hit), and the upright torque and force. Raise the leg and trunk stiffness for a stiffer, steadier body; lower them for a looser one. The defaults are the balancer’s own numbers. The detector thresholds (when a foot counts as in the air or the body as at rest) stay inside the balancer.
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:
- The animation skeleton’s pose is read once each time it changes, and each limb is retargeted once per step.
- Characters started together don’t do their every-few-steps work on the same step: each has its own phase.
- A body held on its animation whole skips the joint-limit cushioning and reads its gravity forces every fourth step.
- A body that nothing animates (a corpse, a body lying limp) doesn’t evaluate its animation: the clips pause where they
are and play on when something needs them (
MarionetteAnimator.PauseWhileUnused, on by default; untick it if your own code reads the animation skeleton on a dead or downed body). A dead body also stops hearing its lasting contacts with the floor (OnCollisionStay), which Unity would otherwise send for every contact, every step. - Fitting the feet to the ground takes the last answer of a ray that starts where it last did (within a centimetre, for up to 8 steps) on static ground, so a standing body casts one ray in eight. A static collider that appears under a standing foot is found within those 8 steps; a kinematic deck under a foot is probed every step.
MarionetteAnimator.GhostBonescan drop the bones the rig doesn’t use from the animation skeleton (not with a Humanoid avatar), which helps on models with many twist or face bones. Scripts, colliders and bodies on the model are always removed from its copy.
Level of detail
Each character runs at a tier, picked every physics step (MarionetteCharacter.Tier, counts in RagdollStats):
| Tier | When | Cost |
|---|---|---|
| Full | Near the viewer (main camera, or RagdollLod.Viewer), within the budget | Everything |
| Reduced | Beyond ReducedDistance (25 m), or past the budget | RagdollLod.Reduced: by default at most 4 / 1 solver iterations, and the animation and ground probes every other step |
| Animated | Undisturbed, 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) |
| Dormant | A settled corpse whose links all came to rest | Not 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.
-
Distance.
ReducedDistancemoves characters to Reduced. With a camera as the viewer,OffscreenDistanceScalemakes what is off screen count as further away (2 = it drops a tier at half the distance). -
Budget.
MaxFullCharacterskeeps only that many at Full. The others run Reduced (or animated, withAnimatedOverBudget). The nearest come first. A character hit in the lastHitPriorityTime(2 s) goes ahead of them all, andMarionetteCharacter.LodPriorityweights the distance (2 counts a character as half as far). -
Per tier.
RagdollLod.Full,.Reducedand.Animated(RagdollTierSettings) set:- the solver iterations;
AnimationInterval: the animation skeleton is evaluated every that many steps. It’s the largest cost of a standing character after the physics. 2 halves it, and the root motion is shared out over the steps, so a walk still covers the same ground;GroundProbeInterval;FitGround(fitting the animation to stairs and slopes);Interpolate.
-
Per character.
MarionetteCharacter.LodMode(also on theActiveRagdollinspector) picks one of:Auto;AlwaysFull(the player, a boss);NeverAnimated(every contact must show on it);AnimatedWhenUndisturbed(animation only at any distance).
TierChangedtells you when the tier changes, so you can swap something of your own along with it.
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.
- What shows. The clip as authored, at the frame rate, not the clip retargeted onto the body’s joints (limb chains, joint limits). Going in and out eases over a fifth of a second; on waking, the joints start from the pose that was showing and ease onto the retargeted clip.
- Where it can’t. A pose on top of the animation (a head look with a target, an aim, an arm pose, your own
behaviour with
RunsWhileAnimated) needs the joints. While one poses a joint away from the clip, the body plays through its joints instead, posed every physics step as before, and goes back onto the Animator when it stops. A head look with nothing to look at doesn’t count. So does a model whose bones aren’t at the paths the animation model has them, or whose root already has an Animator with a controller. TurnRagdollLod.AnimatedOnAnimatoroff to always play through the joints.MarionetteCharacter.PlaysOnAnimatorsays which way a body plays. - Culling.
RagdollLod.AnimatedCullingsets the Animator’s culling mode. Always Animate (the default) keeps the colliders on the body off screen. Cull Update Transforms skips posing bodies no camera sees, while their path still moves, and saves the most in a large crowd. - Generic and Humanoid avatars both play. The Animator added to the model’s root is the animation skeleton’s avatar; an Animator already there without a controller is borrowed and put back as it was.
“Undisturbed” means all of these held for AnimatedSettleTime (0.5 s):
- it is held on its animation, whole and eased in;
- it is standing or walking (locomotion
Following); - it hasn’t been hit lately;
- it isn’t touching a wall;
- it is on the ground;
- no other character is within
AnimatedWakeRadius(1.5 m); - nothing on
AnimatedObstacleLayersis in its way (below).
It goes back to full simulation at once, before the cause acts on it, and moves on as the animation was moving it:
- a hit,
KnockDown,Kill,Disturb, a grab, a teleport, a reset; - a dynamic rigidbody or another body running into it (it also gets that push);
- another character coming within the wake radius;
- a wall, prop or kinematic mover in its way: once a step, each animated character sweeps its body (all of them
together, as one batch on the job threads), from above step height to the head, along its motion for
RagdollLod.AnimatedObstacleLookahead(0.3 s). A standing body checks where it stands. Colliders onRagdollLod.AnimatedObstacleLayerscount (by default every layer that raycasts hit). The floor, triggers and characters’ bodies don’t count. Set the layers to nothing to switch it off. Tested walking into a wall (it woke 0.77 m short) and with a kinematic box pushed at a standing body; - anything that starts a behaviour needing the physics body (a stagger, a grip, a get-up);
- its locomotion letting go of the animation.
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:
- static geometry and kinematic movers don’t touch it, and it walks through a wall the way an animated character would (keep it on the NavMesh);
ArticulationBodyvalues of its parts (velocities,worldCenterOfMass,position) are not live: a switched-off link reads zero. Aim a hit with a ray’s point orMarionettePart.CentreOfMass, which is right either way (Hitmoves a point far from the part onto it, and warns once).Collider.attachedArticulationBodyis null. Find the part a ray hit withMarionettePart.TryGetPart(collider, out var part);- code that pushes its links directly must call
ActiveRagdoll.Disturb()(orHit) first, as it must already for a body held on its animation.
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 tier | Ragdoll step, per physics step | Per rendered frame (Animator, hips and feet) |
|---|---|---|
| Through the joints (as before) | 4.1 ms | 0.25 ms (interpolation and frame callbacks) |
| On the visible Animator | 0.93 ms standing, 1.15 ms walking, of which 0.34 ms is the wake checks both share | 0.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:
| Preset | Tiers | Ragdoll step | Physics stage |
|---|---|---|---|
| 1 Everything simulated | 16 Full | 3.0 to 3.4 ms | 1.4 ms |
| 2 Budget of 8 (the rest Reduced, animation every other step) | 8 Full, 8 Reduced | 2.8 ms | 1.4 ms |
| 3 Animation only when undisturbed | 16 Animated | 0.6 ms | 0.2 ms |
| 4 Budget of 8 and animation only past it | 8 Full, 8 Animated | 2.0 ms | 0.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.
| Characters | Ragdoll step | Per character | PhysX per step | Frame rate |
|---|---|---|---|---|
| 16 | 3.3 ms | 205 µs | 1.7 ms | 185 fps |
| 32 | 6.2 to 6.8 ms | 195 to 215 µs | 2.9 ms | 100 fps |
| 64 (about 52 Full, 12 Reduced) | 11.6 to 12.9 ms | 180 to 200 µs | 3.3 to 4.6 ms | 35 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.
- Setup Wizard: the Interpolate transforms checkbox under Body (on by default). From code,
RagdollRigBuilder.Settings.Interpolate. - Existing rigs: tick Interpolate transforms on the
ActiveRagdollinspector (several characters at once work too) or on the wizard’s built view; it adds the component, or enables the one that is there. Unticking disables it and keeps the component. From an editor script,RagdollSetup.SetInterpolation(root, on); at runtime,MarionetteInterpolation.enabled. - Physics is not affected: before each step, teleport and restart the bones are put back in the pose physics left them in, and after a teleport the first steps are drawn as they are, with no blend from the old place.
- Code reading part transforms from
Updatesees the drawn pose, up to a step behind physics.FixedUpdate(after this component’s own, which runs first), andArticulationBodyvalues such asworldCenterOfMassand velocities, see the real one. Raycasts hit the real colliders. - It works with every
RagdollSimulation.Stepping: each simulation’s pose is time-stamped (the fixed step’s time, or the frame’s for a simulation run fromUpdate) and frames are drawn one simulation behind, between the last two. Several simulations in one fixed step, substeps included, count as one. A loop of your own that knows better (a fixed-step accumulator: its remainder over the step) setsRagdollSimulation.InterpolationAlpha. - It does nothing while
Physics.autoSyncTransformsis on (it is off by default). The first one enabled says so in the console. The Validator flags Auto Sync Transforms on a character that interpolates and offers to turn it off. CallMarionetteInterpolation.Snap()after moving the bones by some means other thanActiveRagdoll.Teleport.
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.19f1 | Unity 2022.3.62f3 | |
|---|---|---|
| Pelvis path | 0.00 m | 0.42 to 0.62 m |
| Heading turned | none | 26° to 67° |
| Feet scrubbed | 0.000 m | 0.5 to 1.2 m |
| Yaw rate (rms) | 0.014 rad/s | 0.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)
| Tried | Result |
|---|---|
| Position iterations 12 | still slides |
| Position iterations 16 | still slides after 20 s |
| Position iterations 20 | still: 0.06 to 0.08 m of path, 4° to 6°, yaw 0.01 to 0.02 rad/s |
| Position 30, velocity 8 | still: 0.02 m |
| Velocity iterations 4 or 8 alone | no change |
| Friction 1 or 3 on every collider | no change, if anything worse |
Gains.YawDamping 0 | no 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 heading | less 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:
- For the whole project: set Project Settings > Physics > Default Solver Iterations to 20. An
ArticulationBodytakes this value when it is created and the package reads it from the root link when the character starts. Bodies already in a scene don’t store their own iteration count, so they pick up the new default. - For one character, from code: call
MarionetteCharacter.SetSolverIterations(20, 1)after it starts. Only compile it in for 2022.3 if your project also builds on Unity 6:
#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
- What 20 iterations cost per character. More iterations cost more solver time; see Performance to measure it in your scene.
- Whether hits, staggers and falls feel the same at 20 iterations on 2022.3. The reaction tests were tuned on Unity 6 at the default 6.
- The
Reducedtier caps a body at 4 iterations (RagdollLod.ReducedSolverIterations), and the Mobile sample uses 4. Expect a body standing on its own at those settings to drift on 2022.3. Not measured. - Other 2022.3 patch releases. Only 2022.3.62f3 was measured.
Debugging
- Validator (Tools > Despair Physics > Validator): checks every ragdoll in the open scenes and the project settings, with Fix (and Fix All) for what can be fixed safely.
ActiveRagdollinspector in Play mode: state, balance, last hit, strength, tier and locomotion, live.MarionetteRecorder(Add Component > Despair Physics > Debug): records a character’s balance into a text table every few physics steps and prints it to the console when done. Script the disturbance withAct(once, atActAtseconds) orDrive(every step) so runs compare like for like; Record Again and Copy Table to Clipboard are in its context menu. The columns are listed in its class summary.MarionetteDebugView(Add Component > Despair Physics > Debug > Debug View): draws what the balance is doing. In the Scene view (and the Game view with Gizmos on): the centre of mass with its drop to the floor, its velocity and its capture point (orange cross); the support polygon, the outline of the feet on the ground, green while the centre of mass is over it and red when it is not; foot targets, where each foot stands and where a foot in the air will land; and joint stiffness, a sphere at every joint that is blue when limp, green at the default and red when stiff. Each can be switched off, labels with the numbers can be switched on, and Only When Selected limits it to the selected character. On screen, in the Game view and in player builds, a readout over the head shows the state, tilt, steps left, the support margin, strength, tier and locomotion state. It draws only in Play mode and does nothing while disabled.MarionetteIncidents: a log of the moments worth a second look, for every character (handed to the balancer, knocked by another body, launched, fell). Off and free by default:MarionetteIncidents.Enabled = true, play, thenDebug.Log(MarionetteIncidents.Take()).- Profiler: see Performance for the markers.
Troubleshooting
| Symptom | What to check |
|---|---|
| The character falls over at once | Run 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 easily | Its 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 walks | MarionetteLocomotion 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 Scenes | The 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 Scenes | They need the Unity UI package (com.unity.ugui). The Input System package is optional. |
| Bodies jitter or sink into each other | The ragdoll layer must collide with itself (the Validator offers the fix), and Physics.simulationMode should be FixedUpdate. |
| A character moved by script snaps back | Never 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-air | The 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 hard | RagdollStepping.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 spot | The solver needs about 20 position iterations there (Unity 6 manages with 6). See Unity 2022.3: standing bodies drift. |
| A Generic rig doesn’t map | Open 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
- The rig is a fixed 20-part humanoid layout. A skeleton needs a neck, two clavicles, and three bones per limb (upper, lower, hand or foot). Digitigrade legs, extra limbs and non-humanoids are out of scope.
- 3ds Max Biped maps only with Triangle Pelvis and Triangle Neck on (or through a Humanoid avatar). By default, Biped hangs the legs from the spine and the clavicles from the neck. That is a different tree from the physics rig’s, and re-parenting bones would break animation.
- Merged spine segments bend at one joint. Spine bones that ride along keep their rest pose on the body, and so do twist bones chained between joints (Daz, Rigify), so limb twist shows at the next joint.
- Supported height: 0.6× to 2.5× the 1.8 m reference (1.1 m to 4.5 m) for a body fitted with Scale to Rig, tested against flat-ground shoves only. Stepping and balance distances are in metres tuned for an adult, so a small body left unfitted can fall over; the validator warns about bodies outside the range. A fitted small body rarely blows up under a shove: in 1,800 test shoves on the sample character (40 to 150 N·s, from the front and the side, 0.6× to 1×), two hard shoves at 0.6× did, and none at 0.65× or above. A small body left unfitted blows up far more often. The character stands back up when it happens.
- Scale to Rig brings a body close to the reference, not onto it: the balancer has edges where one small step comes or goes, and the further a body is from the reference, the more of them it meets. The Rig Calibrator closes much of what is left.
- Walking on planned steps (
BalanceSteering) holds a pace only with a push from the game, and each rig has a slowest pace it walks well: on the test rig about 1 m/s (asked for less, it walks at about that). See Walking from gameplay. - On Unity 2022.3, a body standing on its balance alone drifts at the default 6 solver iterations and needs about 20. The package doesn’t raise them. See Unity 2022.3: standing bodies drift.
- With
RagdollStepping.Substepped, Unity’sRigidbodyinterpolation skips the steps run in substeps. See Interpolation for the fix. - A character playing as animation only (
RagdollTier.Animated) passes through static geometry and through other characters’ bodies until it wakes. It looks for walls and kinematic movers only along its own motion, a step at a time (AnimatedObstacleLookahead). So a mover faster than that look-ahead, coming from the side, can reach it first. Anything below step height (a third of the hip height) is left to the feet. - Name presets were checked against each exporter’s documented names, not against real exported files. A rig that renames bones on export falls through to the Humanoid avatar, or to the heuristics if you opt in.
- The sample materials use one simple solid colour shader per render pipeline (Built-in, URP, HDRP), switched automatically. The Built-in and URP ones take the scene’s main directional light, its shadows and the ambient light; the URP one ignores additional lights. The HDRP one is unlit, with fixed shading baked into the colour, so it follows no scene light and receives no shadows. The scenes’ own lighting and sky are set up for Built-in and URP and were not adapted for HDRP. The package itself is render-pipeline agnostic.
- Custom reactions (
CustomReaction) and custom components drive the character from its events and public calls, and a custom reaction can pose a region of the body (PoseRegion). For joint control beyond that, derive fromRagdollBehaviourand schedule it withAddBehaviour/StartBehaviour(see Your own behaviours). - A custom locomotion is animation-driven: it chooses clips, speeds and a path through
LocomotionHost, and the stepping balancer takes over when the body is disturbed. There is no public way to command a step or to walk a body procedurally (physics-driven walking is out of scope). - The package’s own behaviours and effectors are internal, so a harness outside the package cannot drive them
directly; see Public API for what is supported. The reactions’ numbers are public. A reaction of your
own derives from
CustomReactionand acts through the public calls, and may pose a region (ActiveRagdoll.PoseRegion). A behaviour of your own derives fromRagdollBehaviour, which is the public way to write joint targets (see Your own behaviours).