SphereCastCommand does not hit query overlapping colliders at cast origin

So, Physics.SphereCastNonAlloc actually hits colliders when SphereCast ray origin is inside collider.
Manual states that it should not, but it still does, and its handy.

Scheduled SphereCastCommand does not return these colliders at all.
And OverlapSphereCommand is only available on 2022.2+.

Oof.

Is there a way to otherwise check if query is overlapping in a job? Or its gather entities & check manually?

Most-likely this will not be helpful for the average Unity user due to use-case specifics and basic physics engine math knowledge requirements. But if anyone encounters same issue, these are some hints how to solve it.

So, what seems to work for now (shallow tests, our use-case):

For projectiles / test against static colliders & prevent clipping:

  • Extra RaycastCommand that is cast from the same origin / direction / distance;
  • If hit is positive, add RaycastHit results to the hit buffer.
  • Hit buffer is then sorted by the distance after other systems has done writing other hit data;

Theoretically its still possible for the object to get clipped at some extreme angles / speed values, but its much more improbable. This will not register hits that adjacent to the sphere of course, but its visually - close enough.

For projectiles that hit dynamic targets (e.g. enemies when projectile is inside collider OR no collider is available at all):

  • Prepare / Gather dynamic targets using some lookup like a Native Octree (AABB);
  • Query objects in AABB of the initial SphereCastCommand;
  • Do raycast against those hits, include hits at origin;
  • Perform per skinned mesh / mesh raycast to gather improved precision hits; (optional)
  • Write results to the hit buffer, sort afterwards;

Hopefully either SphereCastCommand gets improved, or OverlapSphereCommand gets backported to 2021 LTS.

2 Likes