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

Implementing Foot Placement with Raycasting

Learners will cast rays from the character's feet to detect uneven terrain geometry and calculate necessary height offsets.

In this lesson, you’ll learn how to dynamically adjust your character's foot height to match uneven terrain, ensuring your character’s feet never "float" above or clip through the ground.

The Concept of Foot Raycasting

When a character walks on slopes or stairs, the animation remains fixed at a specific height. To fix this, we use Raycasting. By firing a ray downwards from a point slightly above each foot, we can detect the exact distance to the ground surface. We then use this distance to calculate an offset, which we pass to our Inverse Kinematics (IK) solver to "push" the foot precisely onto the terrain geometry.

Calculating the Offset

The logic involves three steps:

  1. Cast the Ray: Shoot a Ray downward from a target position (usually the hip or knee level).
  2. Hit Detection: Use Physics.Raycast to find the ground. If it hits, record the hit.point.y (the world height of the ground).
  3. Offset Calculation: Subtract the current foot position from the ground height to find the required vertical adjustment.

Here is a simplified approach to gathering that target position:

void UpdateFootPosition(Transform footTarget, Transform rayOrigin)
{
    Ray ray = new Ray(rayOrigin.position, Vector3.down);
    if (Physics.Raycast(ray, out RaycastHit hit, maxRayDistance, groundLayer))
    {
        // Calculate the height difference between the hit point and the foot
        float offset = hit.point.y - footTarget.position.y;
        
        // Apply this offset to your IK solver's position weight or target transform
        AdjustIKPosition(offset);
    }
}

Why Raycasting?

Unlike static colliders, raycasting provides a real-time data point. If your character steps onto a rock or a step, the ray detects the change in terrain height instantly, allowing the IK system to adjust the leg extension smoothly. This creates a much more grounded and professional look for your characters, especially when navigating complex level designs or varied landscapes. By combining these measurements with the Animation Rigging tools we’ve explored, you can create a character that feels physically present in your game world.

Key Takeaway: Raycasting acts as the "eyes" of your character’s feet, providing the precise distance data needed for IK to keep them firmly planted on uneven surfaces.