# 4. Procedural Stepping and Secondary Motion Part of [[Procedural Animation and IK]]. Previous: [[3. Look-At Interest Targets and Aim Chains]]. Next: [[5. Ragdoll Setup and Blending]]. > [!warning] Code not compiled > Scripts use `TwoBoneIKConstraint` targets only through plain `Transform`s, plus `Physics.Raycast`, coroutines and the Input System `Keyboard` class. Not compiled or play-tested. A spider, a crab robot or a mech has no walk clip that fits every slope. Instead of animating legs, you **plant feet in the world and step when a foot falls too far behind**. This is the technique behind most procedural creatures, and it is a great classroom demo because the whole system is about 150 lines. ## 4.1 How it works 1. Each leg has a **Two Bone IK** constraint whose **target lives in world space** (unparented at runtime), so the foot stays where it was planted while the body moves. 2. Each leg also has a **home** point, a child of the body, marking where the foot would ideally be. 3. Every frame, project the home point onto the ground (raycast). If the planted foot is more than `stepDistance` from that projected point, **step**: move the target along an arc to the new point over `stepDuration`. 4. Legs are in **gait groups**. A group only steps when no leg of another group is mid-step. Two groups gives an alternating trot (quadrupeds) or a tripod gait (insects, three legs per group). 5. The **body** rises, lowers and tilts to match the planted feet. ## 4.2 Build the creature Any generic rig with 4-8 two-segment legs works. A gray-box version: a capsule body with cylinders for legs, each leg a 3-bone chain (hip, knee, foot) under the body. ``` Spider (SimpleCreatureMover, ProceduralLegStepper, ProceduralBodyAdjuster) ├── Body <- visual body + leg bones; ProceduralBodyAdjuster moves this, not the root │ ├── Leg_FL_Hip > Leg_FL_Knee > Leg_FL_Foot │ ├── ... │ └── Homes │ ├── Home_FL (where the front-left foot rests, about 0.6 m out) │ └── ... └── Rig_Legs (Rig; RigBuilder + Animator on Spider) ├── IK_FL TwoBoneIKConstraint (root=Hip, mid=Knee, tip=Foot) │ ├── Target_FL │ └── Hint_FL (above and outward of the knee, so knees bend up) └── ... ``` 1. Add **Animator** (no controller needed) and **Rig Builder** to `Spider`. Animation Rigging needs an Animator to run its jobs even when no clip plays. 2. Create `Rig_Legs` with a **Rig** component and add it to the Rig Builder's layers. 3. One **Two Bone IK** per leg; use **Auto Setup from Tip Transform**, then move each **Hint** above the knee. 4. Place a `Home_*` empty under `Body/Homes` at each foot's rest position. 5. Assign legs to gait groups: for a quadruped, FL + BR = group 0, FR + BL = group 1. For a hexapod: FL, MR, BL = 0; FR, ML, BR = 1. ## 4.3 ProceduralLegStepper.cs ```csharp using System.Collections; using UnityEngine; /// <summary> /// Procedural stepping for multi-legged creatures. IK targets stay planted in world space /// and step along an arc when they fall too far from their home point. /// Legs in the same gait group step together; groups alternate. Not compiled in an editor. /// </summary> public sealed class ProceduralLegStepper : MonoBehaviour { [System.Serializable] public class Leg { public string name = "FL"; [Tooltip("The Two Bone IK target. Unparented at Start so it stays in world space.")] public Transform ikTarget; [Tooltip("Child of the body: where this foot wants to be.")] public Transform home; [Min(0)] public int gaitGroup; [System.NonSerialized] public Vector3 planted; [System.NonSerialized] public Vector3 plantedNormal = Vector3.up; [System.NonSerialized] public bool stepping; } [SerializeField] Leg[] legs; [SerializeField] LayerMask groundMask = 1; [SerializeField] float probeUp = 1f; [SerializeField] float probeDown = 2f; [Header("Gait")] [SerializeField] float stepDistance = 0.45f; [SerializeField] float stepDuration = 0.14f; [SerializeField] float stepHeight = 0.15f; [Tooltip("Seconds of velocity to lead the step by, so feet land ahead of the body.")] [SerializeField] float leadTime = 0.25f; Vector3 lastPosition; Vector3 velocity; public int LegCount => legs.Length; public Vector3 FootPosition(int i) => legs[i].planted; public Vector3 FootNormal(int i) => legs[i].plantedNormal; public bool IsStepping(int i) => legs[i].stepping; void Start() { lastPosition = transform.position; foreach (var leg in legs) { leg.ikTarget.SetParent(null, true); // world space from now on if (Ground(leg.home.position, out Vector3 p, out Vector3 n)) { leg.planted = p; leg.plantedNormal = n; } else leg.planted = leg.home.position; leg.ikTarget.position = leg.planted; } } void OnDestroy() { // The targets were unparented; clean them up with the creature. foreach (var leg in legs) if (leg.ikTarget != null) Destroy(leg.ikTarget.gameObject); } void Update() { float dt = Mathf.Max(Time.deltaTime, 1e-5f); velocity = Vector3.Lerp(velocity, (transform.position - lastPosition) / dt, 1f - Mathf.Exp(-10f * dt)); lastPosition = transform.position; Vector3 lead = Vector3.ProjectOnPlane(velocity, Vector3.up) * leadTime; for (int i = 0; i < legs.Length; i++) { Leg leg = legs[i]; if (leg.stepping) continue; leg.ikTarget.position = leg.planted; // planted feet do not move if (!Ground(leg.home.position + lead, out Vector3 desired, out Vector3 normal)) continue; if ((desired - leg.planted).sqrMagnitude < stepDistance * stepDistance) continue; if (AnotherGroupStepping(leg.gaitGroup)) continue; StartCoroutine(Step(leg, desired, normal)); } } bool AnotherGroupStepping(int group) { foreach (var other in legs) if (other.stepping && other.gaitGroup != group) return true; return false; } IEnumerator Step(Leg leg, Vector3 to, Vector3 normal) { leg.stepping = true; Vector3 from = leg.planted; float t = 0f; while (t < 1f) { t = Mathf.Min(1f, t + Time.deltaTime / stepDuration); float eased = t * t * (3f - 2f * t); // smoothstep Vector3 p = Vector3.Lerp(from, to, eased); p += Vector3.Lerp(leg.plantedNormal, normal, eased) * (Mathf.Sin(t * Mathf.PI) * stepHeight); leg.ikTarget.position = p; yield return null; } leg.planted = to; leg.plantedNormal = normal; leg.ikTarget.position = to; leg.stepping = false; // Hook point: footstep audio / dust VFX here (see Footsteps and Surface Audio). } bool Ground(Vector3 around, out Vector3 point, out Vector3 normal) { Vector3 up = transform.up; if (Physics.Raycast(around + up * probeUp, -up, out RaycastHit hit, probeUp + probeDown, groundMask, QueryTriggerInteraction.Ignore)) { point = hit.point; normal = hit.normal; ProcDebug.Cross(point, 0.05f, Color.cyan); return true; } point = around; normal = up; return false; } } ``` ### Things worth explaining in class - **Raycast along the body's up, not world up.** That is what lets the creature walk up a wall if the mover rotates it (the same idea as [[Surface-Walking with an Omnidirectional Player Movement]]). - **`leadTime`** places the new foothold ahead of the body. Without it, feet always land behind and the creature looks dragged. - **Gait groups as a tiny state machine.** Each leg is Planted or Stepping; the only rule is "no two groups stepping at once". That rule is the whole gait. ## 4.4 ProceduralBodyAdjuster.cs ```csharp using UnityEngine; /// <summary> /// Raises, lowers and tilts the body to match the planted feet of a ProceduralLegStepper. /// Moves the Body child, never the root, so the mover's position stays authoritative. /// Not compiled in an editor. /// </summary> public sealed class ProceduralBodyAdjuster : MonoBehaviour { [SerializeField] ProceduralLegStepper stepper; [SerializeField] Transform body; [SerializeField] float bodyHeight = 0.45f; [SerializeField, Range(0f, 1f)] float tiltAmount = 0.7f; [SerializeField] float sharpness = 8f; [SerializeField] float bobPerSteppingLeg = 0.015f; void LateUpdate() { int count = stepper.LegCount; if (count == 0) return; Vector3 avg = Vector3.zero; Vector3 normal = Vector3.zero; int stepping = 0; for (int i = 0; i < count; i++) { avg += stepper.FootPosition(i); normal += stepper.FootNormal(i); if (stepper.IsStepping(i)) stepping++; } avg /= count; normal = normal.sqrMagnitude > 0.0001f ? normal.normalized : transform.up; // Height: average foot height in root space, plus body height, plus a little bob. float localFootY = transform.InverseTransformPoint(avg).y; float targetY = localFootY + bodyHeight + stepping * bobPerSteppingLeg; // Tilt: rotate root-up toward the averaged ground normal, partially. Vector3 localNormal = transform.InverseTransformDirection(normal); Quaternion targetTilt = Quaternion.Slerp(Quaternion.identity, Quaternion.FromToRotation(Vector3.up, localNormal), tiltAmount); float k = 1f - Mathf.Exp(-sharpness * Time.deltaTime); Vector3 lp = body.localPosition; body.localPosition = new Vector3(lp.x, Mathf.Lerp(lp.y, targetY, k), lp.z); body.localRotation = Quaternion.Slerp(body.localRotation, targetTilt, k); } } ``` > [!note] Why LateUpdate > The adjuster reads planted positions after the stepper's `Update` and moves the body before rendering. The Two Bone IK constraints then solve next frame from the new hips. A one-frame lag on body height is invisible at these speeds. ## 4.5 SimpleCreatureMover.cs (test driver) ```csharp using UnityEngine; using UnityEngine.InputSystem; /// <summary> /// WASD test mover for procedural creatures. Moves and turns the root only. /// Not compiled in an editor. /// </summary> public sealed class SimpleCreatureMover : MonoBehaviour { [SerializeField] float speed = 1.5f; [SerializeField] float turnSpeed = 90f; void Update() { var kb = Keyboard.current; if (kb == null) return; float move = (kb.wKey.isPressed ? 1f : 0f) - (kb.sKey.isPressed ? 1f : 0f); float turn = (kb.dKey.isPressed ? 1f : 0f) - (kb.aKey.isPressed ? 1f : 0f); transform.Rotate(0f, turn * turnSpeed * Time.deltaTime, 0f, Space.Self); transform.position += transform.forward * (move * speed * Time.deltaTime); } } ``` For a real enemy, replace it with a NavMeshAgent ([[NavMesh in Unity 6 (AI Navigation 2.x)]]); the stepper only cares that the root moves. ## 4.6 Secondary motion with Damped Transform Tails, antennae, ponytails, cables and backpack straps should lag behind the body. Animation Rigging's **Damped Transform** does this with no code. The 1.4 manual describes `Damp Position` and `Damp Rotation` as weights where **0 follows the source exactly and 1 does not move at all**. 1. Under a Rig (a new `Rig_Secondary` is tidy), add one child per tail bone with a **Damped Transform** constraint. 2. For bone *i*: **Constrained Object** = tail bone *i*, **Source** = tail bone *i - 1* (the first bone's source is the pelvis or body bone). 3. Start with **Damp Position 0.3**, **Damp Rotation 0.5**, **Maintain Aim on**. Increase damping toward the tip for a whip-like tail. 4. Order the constraint GameObjects from root to tip, so each bone uses its already-damped parent. On the spider, two Damped Transforms on each antenna (source = head bone) make it feel alive when it turns; on a humanoid, the same on a ponytail or a holstered weapon. ## 4.7 Check - [ ] Walking forward, feet land ahead of the body and never more than one gait group lifts at once. - [ ] Turning on the spot makes the feet shuffle (they leave their home radius as the body rotates). - [ ] On the 20 degree ramp, the body tilts but not fully (tiltAmount 0.7). - [ ] Antennae swing past and settle when the creature stops. ## Sources - `TwoBoneIKConstraintData` (1.4): https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.Animations.Rigging.TwoBoneIKConstraintData.html - Damped Transform (1.4.1 manual): https://docs.unity3d.com/Packages/[email protected]/manual/constraints/DampedTransform.html - `DampedTransformData` (1.4): https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.Animations.Rigging.DampedTransformData.html - Input System `Keyboard` (1.20): https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.InputSystem.Keyboard.html