# Find the intersect points between a rectangle and a segment

I want to find the (maximum 2) intersect points between a segment (a line that is of finite length defined by a starting and an ending points) and a rectangle. Both of them are "floating" in 2-D space without being bounded to the center (0,0) or to any of the axes.

Is there an easier way to find the intersection points except for continuing all the lines to be infinite, find the intersection points between the lines of the rectangle and the line of the segment and then check if the points are on the perimeter of the rectangle?

The rectangle is defined by 4 points.

But if for example you expect an intersection to be rare, it may be worth while to first make a simpler test if there is an intersection at all. If the line segment is given by endpoints $(x_1, y_1)$ and $(x_2, y_2)$ then a point $(x,y)$ is on the same straight line iff $u\cdot x+v\cdot y+w=0$ with $u:=y_2-y_1$, $v:=x_1-x_2$, $w:=x_1 y_2-x_2y_1$. Moreover, the two half planes defined by the line can be distinguished by whether $u\cdot x+v\cdot y+w>0$ or $u\cdot x+v\cdot y+w<0$. Thus: plug the four vertices of your rectangle into the exppression $u\cdot x+v\cdot y+w$. If all four vertices produce a negative result (or all foru produce a positive result), then trivially there is no intersection at all.
• And how can I find the coordinates of intersection points? – kolobok Sep 9 '14 at 14:45