Line and rectangle intersection

1.6k Views Asked by At

I have a rectangle and a line segment inside the rectangle, and the line can be extended on both sides. I know the coordinates of the rectangle's four vertices as well as the line's two vertices.

I try to write a function that would return the coordinates of the two intersection points of the line segment and the rectangle. The language I am using is python. The problem is that I am not sure which side of the rectangle the line would intersect with. So it makes my function to be extremely complex, and I am not sure if I've covered all the cases or not.

Is there an algorithm for me to do this?

1

There are 1 best solutions below

0
On

Your rectangle can be characterized as xmin, xmax, ymin, and ymax. Find the equation of your line (see this). Then solve your line for each of xmin, xmax, ymin, and ymax. Eliminate solutions that have x < xmin or x > xmax or y < ymin or y > ymax.