I'd like to know if a line segment intersects another, where the 2nd line segment will only be horizontal or vertical.

There are similar questions about general line segments, but this constraint may be able to reduce the computation required.

Ideally with only real numbers being used, not vectors. The inputs should be 8 numbers, being the 'x' and 'y' positions of the ends of the 2 lines. This is not homework.

  • $\begingroup$ What is the computation you're asking about? $\endgroup$ – Hayden Mar 27 '14 at 19:20
  • $\begingroup$ please be more specific $\endgroup$ – Amit Mar 27 '14 at 19:21
  • $\begingroup$ What exactly are your inputs? Two pairs of points? Intercepts and slopes? $\endgroup$ – user7530 Mar 27 '14 at 19:33
  • $\begingroup$ 2 line segments, as four end points, as 8 numbers. $\endgroup$ – alan2here Mar 27 '14 at 19:47

If the oblique line segment goes from $(x_1,y_1)$ to $(x_2,y_2)$, you can write its equation using the two point form as $y-y_1=\frac {y_2-y_1}{x_2-x_1}(x-x_1)$. Now if your second line segment goes from $(x_3,y_3)$ to $(x_3,y_4)$ (note the equality of the two $x$ coordinates-this is a vertical segment), you can find the $y$ coordinate where the vertical line would hit the oblique line, then check if it is within both segments. The intercept point is $(x_3,y_i)$ with $y_i=y_1+\frac {y_2-y_1}{x_2-x_1}(x_3-x_1)$. Now check whether ($y_3 \le y_i \le y_4$ or $y_3 \ge y_i \ge y_4$) and ($y_1 \le y_i \le y_2$ or $y_1 \ge y_i \ge y_2$). The case for the line segment being horizontal is similar.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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