## 1. Introduction

In this tutorial, we’ll show how to check if a line segment intersects a rectangle.

## 2. Intersection

Let’s say that the segment’s endpoints are and . Similarly, let , , , and be the rectangle’s corners.

We say that the segment intersects the rectangle if has at least one common point with at least one rectangle’s side. For example:

So, the idea is to check if intersects , , , or . If we find an intersection with any side, we don’t need to check the rest.

## 3. The Intersection of Two Segments

So, let’s see how we can check if intersects . The steps will be the same for the three remaining sides.

If intersects , there will be at least one point that belongs to both and :

Focusing on the triangle and treating , , , , and as vectors directed from the origin, we see that the following must hold:

The condition ensures that belongs to both segments.

### 3.1. Solving a Linear System

If , , , and , we get a system of two linear equations:

(1)

The next step is to solve it for and .

### 3.2. Interpreting the Solution

If the system has no solution, doesn’t intersect .

If there’s a unique solution such that and , then they intersect at a single point .

If there’s more than one solution, we’ll get a range of values for and . If the ranges include values from , and coincide at least partially. In particular, if the ranges are completely inside , we have , , or both.

### 3.2. Algorithm

Here’s our algorithm:

So, we start with one side and check all the others iteratively until we either find an intersection or test all of them without success.

Since we deal with a fixed number of dimensions, solving systems takes  time, so the complexity of the entire algorithm is also .

### 3.3. What if the Segment Is Inside the Rectangle?

We set out the problem and formulated our algorithm to test only if has a mutual point with the rectangle’s boundary.

On the other hand, if we want to cover the rectangle’s interior, we need to extend our algorithm. The already formulated pseudocode deals with all the cases except when lies inside the interior of .

To handle it, we note that is inside the rectangle only if and are linear combinations of the rectangle’s directed non-parallel sides such that all the coefficients are between 0 and 1:

We can take any two adjacent sides as the vectors as long as we direct them so that the interior points have positive coefficients.

To check that, we solve two linear systems we derive from:

and

If both have single solutions and is in the interior of .

## 4. Conclusion

In this article, we talked about how to check if a line segment intersects with a rectangle. We differentiated between two cases: in the first one, we considered if the segment intersects the rectangle’s boundary, and in the second one, the case where we covered the intersections with the interior as well.