Skip to content

Instantly share code, notes, and snippets.

@JohannesMP
JohannesMP / 2DLineRectIntersection.md
Last active April 18, 2024 00:53
[C#, Unity3D] An optimized solver for intersection between a Line Segment and a Rect in 2D space with spacial partitioning.

Overview

For a 2D Unity Project, I needed a really efficient way to get the intersection points between a line segment (as defined by two Vector2) and an axis-aligned Rect in 2D space, where the intersection points are returned as a parametric fraction of the length of the original line segment:

Note how when the line intersects the rect, the green line represents the portion inside the rect, and the parametric representation of the point of intersection along the line is displayed

In my use case the vast majority of lines are either completely inside or completely outside the rect, and so I needed an approach that was very efficient in cases where there is guaranteed no intersection and avoids unecessary raycasts when possible.