CollisionWorld.CastRay() does not work with Collector

I have this code snipped which is supposed to detect when an entity has been clicked on.
Variant A works, which simply returns the closest hit. Variant B does NOT work, even though I use the same ray and a Unity-provided collector.
What confuses me is that both calls use ClosestHitCollider under the hood.
I tried to use every available collector and even wrote a custom one, none detected any entity.

Can anybody help me solve this issue? I probably missed something about the inner workings of the Physics package.

            _currentCollisionWorld = _buildPhysicsWorld.PhysicsWorld.CollisionWorld;

            var ray = _mainCamera.ScreenPointToRay(mouse.position.ReadValue());
            var (origin, end) = (ray.origin, ray.GetPoint(1000f));
            Debug.DrawLine(origin, end, Color.blue);

            var raycastInput = new RaycastInput
            {
                Start  = origin,
                End    = end,
                Filter = CollisionFilter.Default
            };
            var collector = new ClosestHitCollector<RaycastHit>();

            //VARIANT A -> This works!
            if (!_currentCollisionWorld.CastRay(raycastInput, out var closestHit)) return;
            Debug.Log("Variant A!");

            //VARIANT B -> This doesn't work!
            if (!_currentCollisionWorld.CastRay(raycastInput, ref collector)) return;
            Debug.Log("Variant B!");
;

Under the hood the out version just uses a collector

public static bool RayCast<T>(ref T target, RaycastInput input, out RaycastHit closestHit) where T : struct, ICollidable
{
    var collector = new ClosestHitCollector<RaycastHit>(1.0f);
    if (target.CastRay(input, ref collector))
    {
        closestHit = collector.ClosestHit;  // TODO: would be nice to avoid this copy
        return true;
    }

    closestHit = new RaycastHit();
    return false;
}

The issue you’re having is you haven’t set a max fraction value on the collector. Just use 1 like the out version uses and you should have identical behaviour.

2 Likes

Thank you! That seems to have worked.
Sometimes you miss the most obvious stuff :slight_smile: