0
votes

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
Is the rectangle axis-aligned?John Anderson
solve it with all four and check the allowed intervalsNimish Bansal
Yes, the rectangle is axis-alignedYhqjlyr
Do you mean to compute the "possible intersection pts" first for each line, and then check if they are in the legal interval?Yhqjlyr
Write a routine that finds the intersection, if any, of a line segment with a line that contains another segment. Call that routine four times. This reduces the complexity of the code.Rory Daulton

1 Answers

0
votes

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.