Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

In the end, that is what you will have to do.

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.

share|improve this answer
And how can I find the coordinates of intersection points? –  akapelko Sep 9 '14 at 14:45

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.