Interface IRaycastCallback
- Namespace
- Box3D
- Assembly
- Box3D.NET.dll
Receives the shapes a ray cast passes through.
public interface IRaycastCallbackExamples
Collecting every shape a ray passes through, without allocating:
struct CollectAll : IRaycastCallback
{
public int Count;
public RaycastAction OnHit(in RaycastHit hit)
{
Count++;
return RaycastAction.Continue;
}
}
var callback = new CollectAll();
world.Raycast(origin, direction * 50.0f, ref callback);
Console.WriteLine($"passed through {callback.Count} shapes");
Ignoring the shooter's own body:
struct IgnoreBody : IRaycastCallback
{
public Body Ignored;
public RaycastHit Nearest;
public RaycastAction OnHit(in RaycastHit hit)
{
if (hit.Shape.Body == Ignored)
{
return RaycastAction.Ignore;
}
Nearest = hit;
return RaycastAction.ClipTo(hit.Fraction);
}
}
Remarks
Implement this on a struct. The query is generic over the implementing type, so the call is resolved statically and inlined: no delegate is allocated, nothing is boxed, and nothing needs to be kept alive across the call. This is the reason the API takes a callback type rather than a System.Func`2.
Shapes arrive in no particular order, so a callback looking for the nearest hit must either compare fractions itself or return Box3D.RaycastAction.ClipTo(System.Single).
The world is locked while the query runs. Creating or destroying bodies from inside the callback is not allowed; collect what you need and act after the query returns.
Methods
- OnHit(in RaycastHit)
-
Called once for each shape the ray reaches.