Course contentsShow
← Unity Game Development
Lesson 426 of 8286. Animation and CinemachineFree lesson

Applying Two-Bone IK Constraints for Legs

Learners will utilize the Two-Bone IK constraint component to dynamically adjust knee position and foot placement during locomotion.

In this lesson, you will learn how to use the Two-Bone IK Constraint component to dynamically adjust your character's knees and feet so they perfectly conform to uneven terrain during locomotion.

Understanding the Two-Bone IK Constraint

While basic animation clips work well on flat planes, they often suffer from "foot sliding" or floating when a character walks over stairs or slopes. The Two-Bone IK Constraint solves this by forcing the leg to reach for a specific target point—the "IK Goal"—while calculating the necessary rotation for the hip, knee, and ankle bones in real-time.

Setting Up the Constraint

To implement this, ensure you have the Animation Rigging package installed and your character's Rig Builder component configured. Follow these steps:

  1. Create the IK Targets: Create an empty GameObject to act as your IK Goal (where the foot should land) and another as your Hint (which controls the direction the knee points).
  2. Configure the Component: Add the Two-Bone IK Constraint component to your Rig GameObject.
  3. Assign Transforms:
    • Drag your Root, Mid (knee), and Tip (ankle) bones into the corresponding slots.
    • Assign your IK Goal to the Target slot and your Hint to the Hint slot.

Controlling the IK Goal via Script

The magic happens when you update the IK Goal position based on the raycasting logic you learned in previous lessons. When your raycast detects a floor surface, update the target’s position to that hit point:

void Update() {
    if (Physics.Raycast(footPosition, Vector3.down, out RaycastHit hit)) {
        // Move the IK target to the surface of the terrain
        ikGoalTransform.position = hit.point;
        // Keep the knee pointing forward via the Hint transform
        ikHintTransform.position = footPosition + transform.forward;
    }
}

By adjusting the IK Goal in your LateUpdate (or via the Rig Builder’s update order), the constraint component will automatically solve the bone rotations to ensure the foot rests firmly on the ground, regardless of the terrain angle or slope.

Key Takeaway: The Two-Bone IK Constraint bridges the gap between static animation clips and dynamic environments by procedurally repositioning the leg chain to match real-world surface data.