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

Implementing Procedural Animation with Inverse Kinematics

You will use the IK pass to dynamically adjust character limbs to interact with uneven terrain or environmental objects.

In this lesson, you will learn how to use the Unity IK (Inverse Kinematics) pass to dynamically adjust your character's feet to align perfectly with uneven terrain.

Understanding the IK Pass

In standard animation, a "Forward Kinematics" approach dictates that the rotation of the shoulder determines the position of the hand. With Inverse Kinematics (IK), we flip this: we define a target position in world space, and Unity mathematically calculates the joint rotations required to reach that point.

When your character walks over a slope or a staircase, a baked animation clip might cause the feet to hover in the air or clip through the geometry. By using the OnAnimatorIK callback, we can intercept the animation process to "pin" the feet to the ground surface dynamically.

Implementing Foot Placement

To do this, you must first ensure your Animator controller has the IK Pass checkbox enabled on the layer settings. Then, you can implement the logic within your MonoBehaviour script:

void OnAnimatorIK(int layerIndex)
{
    // Set the weight of the IK for the right foot
    animator.SetIKPositionWeight(AvatarIKGoal.RightFoot, 1.0f);
    
    // Raycast to find the ground height
    RaycastHit hit;
    if (Physics.Raycast(rightFootOrigin, Vector3.down, out hit))
    {
        // Adjust the foot to match the terrain height
        animator.SetIKPosition(AvatarIKGoal.RightFoot, hit.point);
    }
}

By casting a ray downward from the hip or the default foot position, we retrieve the exact hit.point on the terrain. We then feed this position into SetIKPosition. Because this happens inside the OnAnimatorIK pass, Unity overrides the keyframed animation for that frame, forcing the limb to snap to your target coordinate before the frame is rendered.

This technique is essential for making characters feel grounded in complex environments where baked animations cannot account for every potential surface variation.

Key Takeaway: The IK pass allows you to override baked animation by dynamically calculating joint rotations to reach a specific world-space target, ensuring limbs interact realistically with environmental geometry.