2D collision detection in Go: contacts, sweeps and raycasts

· gravitton/geometry

A bullet with a radius of half a unit flies fifty units a frame. A wall is two units thick. Ask whether the bullet intersects the wall at the start of the frame, and at the end:

wall := geom.Bx(geom.Pt(20.0, 0.0), geom.Pt(22.0, 10.0))
bullet := geom.Circ(geom.Pt(0.0, 5.0), 0.5)
flight := geom.Vec(50.0, 0.0)

bullet.IntersectsBox(wall)                   // false
bullet.Translate(flight).IntersectsBox(wall) // false

Both false, and the bullet is through the wall. Every game that tests collisions by position has met this, usually as a bug report about a fast enemy walking through a thin floor. The fix is to ask a different question: not “does it overlap now”, but “where along its motion does it first touch”:

hit, ok := geom.Sweep[float64](bullet, flight, wall)
// true, at (20,5), normal ⟨-1,0⟩, 0.39 of the way
bullet.Translate(flight.Multiply(hit.Fraction)) // the bullet stops at (19.5,5)
A bullet drawn at the start and at the end of its flight on either side of a two-unit wall, clear of it in both, and the bullet swept into the wall and stopped against it, with the normal of the hit
The bullet, the wall and the flight above: IntersectsBox is false at both ends, and Sweep stops the bullet at fraction 0.39.

gravitton/geometry answers three kinds of question between any two shapes, and this post is about what each one gives, what the closed boundaries of the earlier post mean for a body at rest, and what the answers cost.

Test, correct, predict

Every shape has Intersects<Kind>, Contains<Kind> and Intersection<Kind> for every other kind, and three package functions take any two shapes:

QuestionCallAnswer
Do they overlap?a.IntersectsBox(b), geom.Intersects(a, b)bool
How deep, and which way out?geom.Collide(a, b)a Contact: the normal, the depth and the points they meet at
Where along a motion do they first touch?geom.Sweep(a, motion, b), ray.HitRectangle(b), geom.Raycast(ray, b)a Hit: the point, the normal there and the fraction of the motion

The first is a test, the second a correction, the third a prediction. A physics step uses all three: predict with a sweep, correct what still overlaps with a contact, and test the rest.

A body at rest

A ball sits on a floor, its bottom exactly on the floor’s top:

floor := geom.Bx(geom.Pt(0.0, 10.0), geom.Pt(30.0, 12.0))
ball := geom.Circ(geom.Pt(5.0, 8.0), 2.0)

ball.IntersectsBox(floor)          // true
geom.Collide[float64](ball, floor) // true, normal ⟨0,-1⟩, depth 0

A touch is a contact. The depth is zero, the contact normal points out of the floor, and the ball has somewhere to push against. This is what the closed boundary of the earlier post buys: with a half-open edge the resting ball would report nothing, gravity would sink it into the floor on the next frame, the contact would push it out, and it would sit there vibrating one rounding error above the ground. A closed boundary within a tolerance makes “resting” a state the library can name.

Sink the ball half a unit, and the contact says how to undo it:

ball = geom.Circ(geom.Pt(5.0, 8.5), 2.0)
contact, _ := geom.Collide[float64](ball, floor)
contact.Normal, contact.Depth             // ⟨0,-1⟩, 0.5
contact.Separation()                      // ⟨0,-0.5⟩, the shortest move out
geom.Distance(ball.Translate(contact.Separation()), floor) // 0
A ball and a crate overlapping a floor, each with its contact normal and contact points and the position it is moved to, and the nearest points of two other shapes with the distance between them
Collide and Nearest as the geometry README draws them, not the numbers above: a ball of radius 1.5 sunk half a unit into a floor, a crate lying flat on it with two contact points, and the nearest points of a pentagon and a capsule.

Separation is the normal times the depth, and after the move the distance to the floor is zero: the same closed boundary that made the resting ball a contact makes the moved ball touch and no more. A crate lying flat gives two points instead of one, (13,10) and (17,10), the ends of the edge the sides share, which is what a solver needs to keep a box from rotating through a floor.

A ray and a bounce

The hero of the first post casts rays from the scout and reflects one off a wall. Against a turned rectangle:

mirror := geom.Rect(geom.Pt(10.0, 5.0), geom.Sz(2.0, 6.0), 0.35)
ray := geom.Ry(geom.Pt(1.0, 7.0), geom.Vec(3.0, -1.0))

hit, ok := ray.HitRectangle(mirror) // at (9.2,4.27), normal ⟨-0.94,-0.34⟩, 2.73 lengths along the ray
ray.Vector.Reflect(hit.Normal)      // ⟨-1.65,-2.7⟩, the bounce
A ray hitting a turned wall, with the normal and the bounce, and a ball swept into a block and stopped at a fraction of its motion
HitRectangle on the mirror and ray above, and beside it Sweep of a different pair, as the geometry README draws them: a ball of radius 1 swept into a block, stopping at fraction 0.45.

The fraction is in units of the ray’s vector, so ray.PointAt(hit.Fraction) is the hit, and the normal is the outward one of the edge, facing the ray. geom.Raycast(ray, mirror) gives the same hit for a shape held as a Shape value. The side the normal faces comes from a cross product, which is why every product is rounded before it is added: a hit that lands on a different edge on arm64 than on amd64 is a bounce that goes a different way.

How a sweep is found

A sweep of a circle against a box could be written by hand, and a sweep of a capsule against a turned rectangle could be written by hand with more effort, and so on for every pair of nine kinds. The library writes it once. The set of motions that bring one convex shape into another is itself a convex shape, their Minkowski difference, and sweeping a by motion into b is a ray cast from the origin against that difference. The difference is never built: a cast needs only its farthest point in a direction, the support, and the support of a difference is the difference of the supports. So Sweep works for any two convex shapes that can name their support, and the package documentation says what it does for the rest: a polygon that is not convex is swept edge by edge, a sector past half a turn as its two halves.

The fraction stops within the tolerance short of the touch, and a sweep of two shapes that already intersect returns nothing, both stated in the documentation. Together they say how the three questions divide the work: a body in free flight is swept, and once the sweep has brought it to a touch, it is a resting contact for Collide to hold, not a motion for Sweep to find again.

What it costs

A test between two shapes whose kinds are known is a method, and the method allocates nothing. The package functions take the Shape interface, so a shape passed to one escapes to the heap:

nsallocations
ball.IntersectsBox(floor)6.70
ball.CollideBox(floor)1170
geom.Collide(ball, floor)1742
geom.Sweep(bullet, flight, wall)5462
ray.HitRectangle(mirror)3960
geom.Raycast(ray, mirror)4111

The same test through the interface, geom.Intersects[float64](ball, floor), allocates twice where the named method allocates nothing. The documentation of every function says so, and the advice follows from it: a loop that knows its types calls the method, and the functions are for the pass over mixed shapes, where the interface is the point.

Half a microsecond per pair is cheap, and a thousand entities have half a million pairs. Which of them are worth the sweep is a different question, with a different structure, in the next post.

What it leaves out

Nothing here moves on its own. There are no velocities, no masses, no restitution, no solver; Contact and Hit are the facts a solver needs, and the library stops at the facts. A game can resolve a contact with one line, as above, and a physics engine can build its islands and its iterations on the same two structs. That part belongs to the engine built on these libraries, and to its own series.

Every number above comes from the code of this post, pinned to geometry v1.23.0, run on an Apple M3 with Go 1.27.4.