Recursive AI

Batch 2D raycasts in C#

OnePhysics is a free, open-source physics library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Use RaycastBatch to check which points have ground beneath them. Each ray reports its nearest hit or a miss.

Terminal
dotnet new console
dotnet add package RecursiveAI.OnePhysics

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneMath;
using RecursiveAI.OnePhysics.Physics2D;
 
var world = new PhysicsWorld2D();
world.AddBox(new(2, 2), at: new(0, 0));
Vector2F down = new(0, -1);
RayInput2D[] rays = [
    new(new(0, 4), down, 8),
    new(new(3, 4), down, 8)];
var hits = new QueryHit2D[rays.Length];
var query = new PhysicsQuery2D(world);
int count = query.RaycastBatch(rays, hits);
for (int i = 0; i < rays.Length; i++)
    Console.WriteLine($"Ray {i}: {hits[i].IsHit}");
Console.WriteLine($"Hits: {count}");

Unzip the example, then dotnet run.

Text
Ray 0: True
Ray 1: False
Hits: 1

The full program

The program builds three boxes and casts four downward rays. Ray 0 crosses two boxes but reports only the nearer one. Ray 1 passes between boxes. Rays 2 and 3 share an origin, but ray 3 is too short to reach the right box. There are no input files; RecursiveAI.OneMath comes with OnePhysics.

C#
using System.Globalization;
using RecursiveAI.OneMath;
using RecursiveAI.OnePhysics.Physics2D;
 
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var world = new PhysicsWorld2D();
var upper = world.AddBox(new(2, 2), at: new(0, 0));
var lower = world.AddBox(new(2, 2), at: new(0, -3));
var right = world.AddBox(new(2, 2), at: new(4, 0));
lower.Layer = 2;
right.Layer = 2;
 
Vector2F down = new(0, -1);
RayInput2D[] rays =
[
    new(new(0, 4), down, 10), // crosses upper and lower
    new(new(2, 4), down, 10), // passes between boxes
    new(new(4, 4), down, 10), // crosses right
    new(new(4, 4), down, 2),  // stops short of right
];
var hits = new QueryHit2D[rays.Length];
var query = new PhysicsQuery2D(world);
int count = query.RaycastBatch(rays, hits);
for (int i = 0; i < rays.Length; i++)
{
    var hit = hits[i];
    if (!hit.IsHit)
    {
        Console.WriteLine($"Ray {i}: miss");
        continue;
    }
 
    string box = hit.Body == upper ? "upper" : hit.Body == lower ? "lower" : "right";
    Console.WriteLine($"Ray {i}: {box} at ({hit.Point.X:F1}, {hit.Point.Y:F1}), {hit.Distance:F1} m");
}
Console.WriteLine($"Hits: {count}/{rays.Length}");
Text
Ray 0: upper at (0.0, 1.0), 3.0 m
Ray 1: miss
Ray 2: right at (4.0, 1.0), 3.0 m
Ray 3: miss
Hits: 2/4

A hit buffer shorter than the input array throws ArgumentException; an invalid ray, such as one with zero direction, throws ArgumentOutOfRangeException naming the ray’s index.

Variations

Look only at one layer

Add this after the final count in the full program. Both the lower and right boxes are on layer 2; the upper box is not. Ray 0 now reaches the lower box instead of stopping at the upper one.

C#
query.Filter = QueryFilter2D.OnLayer(2);
count = query.RaycastBatch(rays, hits);
Console.WriteLine($"Hits on layer 2: {count}");
Console.WriteLine($"Ray 0: {hits[0].Distance:F1} m");
Text
Hits on layer 2: 2
Ray 0: 6.0 m

The short answer

Put the rays in a RayInput2D[] and supply a QueryHit2D[] with room for one result per ray. PhysicsQuery2D.RaycastBatch writes the nearest hit for each ray and returns the number of rays that hit anything. A hit at input index 2 is always in result slot 2, even if ray 1 missed. The count is a summary, not the end index of the hits.

How do you cast multiple 2D rays in different directions?

Every entry has its own origin, direction and maximum distance. For downward ground checks, keep the direction the same and offset each origin horizontally, as in the snippet at the top. To cast a fan from one point, keep the origins the same and change each direction instead. A direction doesn’t have to be a unit vector, but it can’t be zero. Set the length with MaxDistance, not by scaling the vector. Use a distance that matches the question you’re asking: a two-meter probe and a ten-meter probe can legitimately disagree at the same point.

The query guide describes the batch methods as returning “results in input order.” Read the batch when the world isn’t stepping or being modified. The query reads the current scene; it doesn’t move boxes forward in time.

How do you get the closest hit and its distance from a 2D raycast?

Check IsHit before you read Point, Distance or Body. A miss isn’t a hit at the origin: it’s a default result. On a hit, Point is in world coordinates and Distance is how far the ray traveled in meters. A ray that starts inside a shape can hit at distance zero, so checking Distance > 0 in place of IsHit would drop a valid result. If you need all matching hits along one ray, use the separate RaycastAll method rather than expecting multiple entries per ray from the batch.

How do you make a 2D raycast ignore a layer?

Choose what the query can see using its Filter, independently of which layers can collide during simulation. OnLayer(2) limits every ray in the batch to layer 2 as in the variation above; it doesn’t remove or move the upper box. Filtering happens before selecting the nearest matching hit. A single batch shares one filter. If two groups of probes need different rules, submit them as separate batches.

All onephysics recipes