UnityRef is currently in early development. Some features may be incomplete and/or not functioning.

UNITYREF

Your Pit Stop For Solving ANYTHING in Unity

physics

[PhysX] Correcting Effective Reach Logic in Physics.SphereCast

Solution

collisionraycastingphysicstriggersdetection

Unity 2021.x - Unity 6.3.x

Published 19 days ago

Issue

 Developers often miscalculate the effective range of a Physics.SphereCast, leading to premature or delayed hit detection. This usually stems from a misunderstanding of how the maxDistance parameter interacts with the sphere's radius during the sweep operation. This confusion frequently results in RaycastHit.distance returning unexpected values when the sphere overlaps an object at the start of the cast.

Explanation

Physics.SphereCast functions by sweeping a sphere volume through 3D space starting from an origin.

A common error is assuming maxDistance represents the total reach of the volume. In reality, maxDistance specifies only the translation distance of the sphere’s center.

To accurately implement your script, follow these steps:

  1. Define the origin as the center point where the sweep begins.
  2. Set the radius to determine the thickness of the sweep.
  3. Assign maxDistance as the linear length the center will travel along the direction.

The effective reach of the cast is maxDistance + radius. If an object is located at a distance equal to maxDistance + radius, the leading edge of the sphere will contact it at the very end of the sweep.

Additional Tips:

  • If maxDistance is set to 0, the function behaves like Physics.CheckSphere at the origin.
  • Use RaycastHit.distance to find the distance from the origin to the center of the sphere at the moment of impact, not the impact point itself.
  • Avoid using negative values for maxDistance, as this results in undefined behavior.

TL;DR

The maxDistance in a Physics.SphereCast defines the displacement of the sphere's center; the total detection range actually equals maxDistance + radius.


Related Posts Haven't quite found a solution to your problem? We think these posts might help you.

Content inspired by a Unity discussion post.