Finding out whether two line segments intersect each other

57.9k Views Asked by At

I need to know whether or not two line segments intersect. I thought the formula for that is $y = mx + b$, but I don't think that will work for what I need; at least, I think I need to first know whether the line segments intersect, because that formula just gives the point where the two lines will eventually intersect.

For example, say I have two line segments. Line $1$ has a starting point of $(15, 10)$ and its ending point is $(30, 17)$. Line $2$ has a starting point of $(29,5)$ and an ending point of $(33, 14)$. These shouldn't intersect within those coordinates, but, by using $y = mx + b$, I find that they approximately intersect at $(35, 19.5)$.

How can I find out whether these line segments happen to intersect each other?

3

There are 3 best solutions below

3
On BEST ANSWER

The only reason that two lines will not intersect is if they are parallel. Being parallel is the same as having the same slope. So, in your example, line $1$ has slope

$$\frac{17 - 10}{30 - 15} = \frac{7}{15}.$$

Line $2$ has slope

$$\frac{14 - 5}{33 - 29} = \frac{9}{4}.$$

Since these two numbers are not the same, the lines are not parallel, and they intersect somewhere.

Now, if what you are considering is only the line segment between the two points, I would first consider the slopes as we just did. If they are parallel, then for sure you know that they do not intersect. If, however, the slopes are different, then they will intersect in one point. You then need to find this point, and see if it happens in bounds given on the $x$-values.

So, when you find that the lines intersect at the point $(35, 19.5)$, then this intersection is outside the bounds given, since, e.g., your first line only goes from $x = 15$ to $x = 30$. It never reaches $x = 35$.

2
On

If two lines have unequal slope they will intersect in a a point. If two lines have equal slope, they are either disjointly parallel and never intersect, or they are the same line.

3
On

I'm assuming you can already check intersection of lines, as that's already been answered and you seem to understand it fine.

enter image description here

The segments are $AB$ and $CD$. They intersect if their intersection point lies within the darker middle rectangle (i.e. the area in space that they both occupy). In other words, if the intersection point is $(x,y)$, then $x$ must be less than the smallest right-side value (the $x$-coordinate of $AH$ here), and larger than the smallest left-side value ($GB$). Here the check $x>GB_x$ fails, so they don't intersect. The idea is similar for $y$ values, and it has to pass all 4 tests (two for $x$ and two for $y$) before you can conclude that they intersect.