# 2. Foot IK and Ground Alignment
Part of [[Procedural Animation and IK]]. Previous: [[1. Procedural Animation Pipeline and Overlap]]. Next: [[3. Look-At Interest Targets and Aim Chains]].
> [!warning] Code not compiled
> Both scripts were written against the 6000.5 Scripting Reference (`OnAnimatorIK`, `GetIKPosition`, `GetIKRotation`, `SetIKPosition`, `bodyPosition`, `leftFeetBottomHeight`) and Animation Rigging 1.4 (`TwoBoneIKConstraint`). Not compiled or play-tested.
## 2.1 The problem in one picture
Your walk cycle was animated on a flat floor. On stairs the CharacterController capsule stands on the **higher** step, so the foot over the lower step hangs in the air, and the foot over the higher step clips into it. Foot IK fixes this in three moves:
1. **Probe** the ground under each animated foot.
2. **Lower the pelvis** by the largest downward gap, so the lower foot can reach without straightening the knee completely.
3. **Move each foot** to its ground point and tilt it to the surface normal.
Lowering the pelvis is the step beginners leave out. Without it, IK cannot reach a foot that is below the leg's full length, and the leg snaps straight.
## 2.2 Humanoid path: set up the Animator
1. Select your Animator Controller, open the **Base Layer** settings (gear icon) and tick **IK Pass**. Without it, `OnAnimatorIK` is never called for that layer.
2. Put `HumanoidFootIK` (below) on the **same GameObject as the Animator**. `OnAnimatorIK` is sent to scripts on that GameObject.
3. Set **Ground Mask** to your `Ground` layer. Never include the character's own layer, or the probe hits the character's capsule.
### Optional: foot curves for cleaner weights
The script works without curves by preserving the animated foot lift (2.4). For the cleanest result, author when each foot is planted:
1. Select the walk/run FBX, **Animation** tab, pick the clip, expand **Curves**, add `LeftFootIK` and `RightFootIK`.
2. Key them at **1** while the foot is on the ground and **0** while it swings. Two to four keys per cycle is enough.
3. In the Animator Controller, add **Float parameters named exactly** `LeftFootIK` and `RightFootIK`. The 6000.5 manual says a curve drives an Animator parameter with the same name.
4. Tick **Use Foot Curves** on the component.
For idle clips, key both curves at 1.
## 2.3 HumanoidFootIK.cs
```csharp
using UnityEngine;
/// <summary>
/// Humanoid foot IK with pelvis drop, slope alignment and lift preservation.
/// Runs in OnAnimatorIK, so GetIKPosition returns this frame's animated foot (pre-IK).
/// Requires: Humanoid avatar, IK Pass enabled on the Base Layer, script on the Animator GameObject.
/// Not compiled in an editor.
/// </summary>
[RequireComponent(typeof(Animator))]
public sealed class HumanoidFootIK : MonoBehaviour
{
[Header("Ground probe")]
[SerializeField] LayerMask groundMask = 1;
[Tooltip("Probe starts this far above the character root, so it can find a higher step.")]
[SerializeField] float probeUp = 0.5f;
[Tooltip("How far below the root the probe searches. Also the deepest step the feet will reach for.")]
[SerializeField] float probeDown = 0.6f;
[SerializeField] float probeRadius = 0.05f;
[SerializeField] float maxSlopeDegrees = 50f;
[Header("Feet")]
[Tooltip("Extra height on top of the avatar's own foot-bottom height (rubber soles, thick boots).")]
[SerializeField] float extraSoleOffset = 0f;
[SerializeField, Range(0f, 1f)] float rotationWeight = 1f;
[Header("Pelvis")]
[SerializeField] float maxPelvisDrop = 0.4f;
[SerializeField] float pelvisSharpness = 10f;
[Header("Weights")]
[SerializeField, Range(0f, 1f)] float weight = 1f;
[SerializeField] bool useFootCurves = false;
[SerializeField] string leftFootCurve = "LeftFootIK";
[SerializeField] string rightFootCurve = "RightFootIK";
[SerializeField] float weightSharpness = 15f;
[Header("Debug")]
[SerializeField] bool drawDebug = true;
struct FootResult
{
public bool hit;
public Vector3 position;
public Quaternion rotation;
public float deltaY; // target minus animated, negative when the ground is lower
}
Animator anim;
int leftHash, rightHash;
float leftW, rightW, pelvisOffset;
/// <summary>Global weight, e.g. 0 while ragdolling or climbing.</summary>
public float Weight { get => weight; set => weight = Mathf.Clamp01(value); }
void Awake()
{
anim = GetComponent<Animator>();
leftHash = Animator.StringToHash(leftFootCurve);
rightHash = Animator.StringToHash(rightFootCurve);
}
void OnAnimatorIK(int layerIndex)
{
if (layerIndex != 0) return; // only the Base Layer drives feet
float dt = Time.deltaTime;
float wantL = weight * (useFootCurves ? Mathf.Clamp01(anim.GetFloat(leftHash)) : 1f);
float wantR = weight * (useFootCurves ? Mathf.Clamp01(anim.GetFloat(rightHash)) : 1f);
leftW = Damp(leftW, wantL, weightSharpness, dt);
rightW = Damp(rightW, wantR, weightSharpness, dt);
FootResult l = Probe(AvatarIKGoal.LeftFoot, anim.leftFeetBottomHeight);
FootResult r = Probe(AvatarIKGoal.RightFoot, anim.rightFeetBottomHeight);
// Pelvis: drop by the largest downward gap among weighted, grounded feet.
float drop = 0f;
if (l.hit) drop = Mathf.Min(drop, l.deltaY * leftW);
if (r.hit) drop = Mathf.Min(drop, r.deltaY * rightW);
drop = Mathf.Max(drop, -maxPelvisDrop);
pelvisOffset = Damp(pelvisOffset, drop, pelvisSharpness, dt);
anim.bodyPosition += Vector3.up * pelvisOffset; // world space, only valid inside OnAnimatorIK
Apply(AvatarIKGoal.LeftFoot, l, leftW);
Apply(AvatarIKGoal.RightFoot, r, rightW);
}
FootResult Probe(AvatarIKGoal goal, float footBottomHeight)
{
var result = new FootResult();
Vector3 animated = anim.GetIKPosition(goal);
Quaternion animatedRot = anim.GetIKRotation(goal);
float rootY = transform.position.y;
float sole = footBottomHeight + extraSoleOffset;
// How high the animation lifts this foot above a flat floor at the root.
// Re-applying it on top of the real ground keeps swing arcs alive without curves.
float lift = Mathf.Max(0f, animated.y - (rootY + sole));
Vector3 origin = new Vector3(animated.x, rootY + probeUp, animated.z);
float distance = probeUp + probeDown;
if (Physics.SphereCast(origin, probeRadius, Vector3.down, out RaycastHit hit,
distance, groundMask, QueryTriggerInteraction.Ignore)
&& Vector3.Angle(hit.normal, Vector3.up) <= maxSlopeDegrees)
{
// SphereCast reports the contact point; use it, not the sphere centre.
float groundY = hit.point.y;
result.hit = true;
result.position = new Vector3(animated.x, groundY + sole + lift, animated.z);
result.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal) * animatedRot;
result.deltaY = result.position.y - animated.y;
if (drawDebug)
{
ProcDebug.Line(origin, hit.point, Color.green);
ProcDebug.Cross(result.position, 0.05f, Color.yellow);
}
}
else if (drawDebug)
{
ProcDebug.Ray(origin, Vector3.down, distance, Color.red);
}
return result;
}
void Apply(AvatarIKGoal goal, FootResult foot, float w)
{
if (!foot.hit || w <= 0.001f)
{
anim.SetIKPositionWeight(goal, 0f);
anim.SetIKRotationWeight(goal, 0f);
return;
}
anim.SetIKPositionWeight(goal, w);
anim.SetIKRotationWeight(goal, w * rotationWeight);
anim.SetIKPosition(goal, foot.position);
anim.SetIKRotation(goal, foot.rotation);
}
static float Damp(float current, float target, float sharpness, float dt)
=> Mathf.Lerp(current, target, 1f - Mathf.Exp(-sharpness * dt));
}
```
### Why each piece is there
- **Probe from root height, not foot height.** On stairs up, the animated foot is *inside* the next step. Starting `probeUp` above the root finds the step's top face.
- **SphereCast instead of Raycast.** A 5 cm sphere does not fall through gaps between rocks and gives a smoother normal on stair edges.
- **Lift preservation.** `lift` is how far the clip raises the foot above a flat floor. Adding it back on top of the real ground keeps the swing arc, so you do not need curves to stop swinging feet from being pulled down. Curves are still better on fast runs.
- **`Mathf.Exp` damping.** `Lerp(a, b, 1 - exp(-k*dt))` is frame-rate independent; a plain `Lerp(a, b, k*dt)` is not.
- **Pelvis uses the weighted delta.** A foot in swing (curve 0) does not pull the body down.
## 2.4 Tuning on the IK gym
| Symptom | Fix |
|---|---|
| Feet float 2-3 cm above ground | Lower `extraSoleOffset` (it can be negative); check the avatar's foot bottom height in the Avatar configuration |
| Knee snaps straight on the lower stair | Raise `maxPelvisDrop`; make sure the pelvis delta is being applied (log `pelvisOffset`) |
| Body bobs up and down on stairs | Lower `pelvisSharpness` (6-8) |
| Foot flips on stair edges | Lower `maxSlopeDegrees` or increase `probeRadius` |
| Feet stick to the ground while running | Turn on foot curves |
**Character Controller step offset:** leave **Step Offset** at about 0.3 for a 1.8 m character. Foot IK hides the step; it does not replace the controller's ability to climb it ([[3. CharacterController Implementation]]).
## 2.5 Generic rig path: Animation Rigging foot planter
For a non-humanoid (a robot, a dinosaur) there is no `OnAnimatorIK`. Use one **Two Bone IK** constraint per leg and move its target from script.
### Hierarchy
```
Dino (CharacterController, RigFootPlanter)
├── Model <- Animator + RigBuilder live here; script offsets its local Y (pelvis drop)
│ ├── Armature ...
│ └── Rig_Feet <- Rig, assigned in RigBuilder layers
│ ├── LeftLegIK TwoBoneIKConstraint (root=thigh, mid=shin, tip=foot)
│ │ └── LeftFootTarget
│ └── RightLegIK
│ └── RightFootTarget
```
Use **Auto Setup from Tip Transform** on each Two Bone IK ([[5.Animation Rigging and Script IK]] 5.4), then delete or ignore the generated Hint if the knee bends correctly without it.
### Why curves are required here
In `Update`, the foot bone holds **last frame's post-IK pose**, not this frame's animation. There is no `GetIKPosition` equivalent. So the planter cannot tell a swinging foot from a planted one by looking at it, and needs a `LeftFootPlant` / `RightFootPlant` curve (2.2) plus matching Animator float parameters.
### RigFootPlanter.cs
```csharp
using UnityEngine;
using UnityEngine.Animations.Rigging;
/// <summary>
/// Plants generic-rig feet with Animation Rigging Two Bone IK constraints.
/// Weights come from authored "plant" curves because Update only sees last frame's pose.
/// Offsets a model child down for pelvis drop. Not compiled in an editor.
/// </summary>
public sealed class RigFootPlanter : MonoBehaviour
{
[System.Serializable]
public class Leg
{
public TwoBoneIKConstraint ik;
[Tooltip("Animator float parameter driven by a clip curve: 1 planted, 0 swinging.")]
public string plantParameter = "LeftFootPlant";
[System.NonSerialized] public int hash;
[System.NonSerialized] public float weight;
[System.NonSerialized] public Quaternion tipRestLocal; // tip rotation relative to character root
}
[SerializeField] Animator animator;
[Tooltip("Child that holds Animator and skeleton. Its local Y is lowered for pelvis drop.")]
[SerializeField] Transform modelRoot;
[SerializeField] Leg[] legs;
[SerializeField] LayerMask groundMask = 1;
[SerializeField] float probeUp = 0.6f;
[SerializeField] float probeDown = 0.8f;
[SerializeField] float soleHeight = 0.06f;
[SerializeField] float maxPelvisDrop = 0.35f;
[SerializeField] float sharpness = 12f;
Vector3 modelRestLocal;
float pelvis;
void Awake()
{
modelRestLocal = modelRoot.localPosition;
foreach (var leg in legs)
{
leg.hash = Animator.StringToHash(leg.plantParameter);
// Capture the tip's bind-pose rotation relative to the root once,
// so target rotations never accumulate frame over frame.
leg.tipRestLocal = Quaternion.Inverse(transform.rotation) * leg.ik.data.tip.rotation;
}
}
void Update()
{
float dt = Time.deltaTime;
float lowest = 0f;
foreach (var leg in legs)
{
TwoBoneIKConstraintData data = leg.ik.data; // struct copy; Transforms inside are references
float planted = Mathf.Clamp01(animator.GetFloat(leg.hash));
Vector3 tip = data.tip.position; // last frame's final position
Vector3 origin = new Vector3(tip.x, transform.position.y + probeUp, tip.z);
if (Physics.Raycast(origin, Vector3.down, out RaycastHit hit, probeUp + probeDown,
groundMask, QueryTriggerInteraction.Ignore))
{
data.target.position = hit.point + hit.normal * soleHeight;
data.target.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal)
* (transform.rotation * leg.tipRestLocal);
float delta = (hit.point.y + soleHeight) - (transform.position.y + soleHeight);
lowest = Mathf.Min(lowest, delta * planted);
ProcDebug.Line(origin, hit.point, Color.green);
}
else
{
planted = 0f; // nothing to stand on: let the animation play
ProcDebug.Ray(origin, Vector3.down, probeUp + probeDown, Color.red);
}
leg.weight = Mathf.Lerp(leg.weight, planted, 1f - Mathf.Exp(-sharpness * dt));
leg.ik.weight = leg.weight;
}
lowest = Mathf.Max(lowest, -maxPelvisDrop);
pelvis = Mathf.Lerp(pelvis, lowest, 1f - Mathf.Exp(-sharpness * 0.6f * dt));
modelRoot.localPosition = modelRestLocal + Vector3.up * pelvis;
}
}
```
**Rotation weight:** if the foot orientation looks wrong on your rig (bone axes differ), set the constraint's **Target Rotation Weight** to 0 and let the animation keep the foot's rotation; position alone already fixes floating.
## 2.6 Check on the gym
- [ ] Standing half on a 25 cm step: both soles touch, the hips drop, neither knee locks straight.
- [ ] Walking up and down stairs: no foot inside a step face.
- [ ] Standing on the 20 degree ramp: soles parallel to the ramp.
- [ ] Jumping: set `Weight = 0` while airborne (from your controller's grounded flag) so feet do not reach for the ground mid-air.
## Sources
- `MonoBehaviour.OnAnimatorIK` (6000.5): https://docs.unity.com/en-us/engine/6000.5/script-reference/unityengine/monobehaviour/onanimatorik
- `Animator.GetIKPosition` (6000.5): https://docs.unity.com/en-us/engine/6000.5/script-reference/unityengine/animator/getikposition
- `Animator.bodyPosition` (6000.5): https://docs.unity.com/en-us/engine/6000.5/script-reference/unityengine/animator/bodyposition
- `Animator.leftFeetBottomHeight` (6000.5): https://docs.unity.com/en-us/engine/6000.5/script-reference/unityengine/animator/leftfeetbottomheight
- Curves on imported clips (6000.5): https://docs.unity.com/en-us/engine/6000.5/manual/animation-section/animation-mecanim/animation-clips/animation-curves-on-imported-clips
- `TwoBoneIKConstraintData` (1.4): https://docs.unity3d.com/Packages/
[email protected]/api/UnityEngine.Animations.Rigging.TwoBoneIKConstraintData.html