[PhysX] Correcting Effective Reach Logic in Physics.SphereCast
Solution
Unity 2021.x - Unity 6.3.x
Published 19 days ago
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.
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:
- Define the
originas the center point where the sweep begins. - Set the
radiusto determine the thickness of the sweep. - 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.CheckSphereat theorigin. - Use
RaycastHit.distanceto find the distance from theoriginto 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.