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

Aligning Feet to Surface Normals

Students will rotate foot bones based on ground surface normals to ensure character feet sit flush against sloped environments.

In this lesson, you will learn how to procedurally tilt your character's feet to match the angle of the terrain, ensuring they sit flush against slopes rather than clipping through them.

The Problem of Static Feet

When using basic Inverse Kinematics (IK), you might successfully position a character's foot at the correct height, but the foot often remains perfectly horizontal. On a steep hill, this results in the heel or toe hovering in mid-air. To fix this, we need to extract the "tilt" (normal) of the ground surface and apply that rotation to the foot bone.

Calculating and Applying the Rotation

After performing your raycast to find the ground's position (which we covered in the previous lesson), the RaycastHit struct provides a normal vector. This vector points directly away from the surface.

To align the foot, you must calculate a rotation that turns the foot bone to align its "up" direction with the ground's normal. We use Quaternion.FromToRotation to find the difference between the character's default up-axis (usually Vector3.up) and the ground's normal.

Here is how you apply this to your foot bone during an OnAnimatorIK pass:

// Assuming 'hit' is the RaycastHit from your ground check
if (hit.collider != null)
{
    // Calculate the target rotation based on surface normal
    Quaternion targetRotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
    
    // Apply this as an offset to the foot's current orientation
    footBone.rotation = targetRotation * footBone.rotation;
}

Smoothing the Transition

Simply snapping to the normal can look jarring as the character walks over uneven terrain. It is best to wrap this rotation in a Quaternion.Slerp or Lerp to interpolate between the foot's current rotation and the new, aligned rotation. This creates a natural, fluid transition as the foot contacts the ground, allowing your character to navigate rocky or sloped environments with high visual fidelity.

Key Takeaway: By multiplying the foot bone’s rotation by a Quaternion derived from the surface normal, you transform a rigid animation into a reactive, terrain-aware movement system.