How can I check if 2 segments intersect?
I've the following data:
Segment1 [ {x1,y1}, {x2,y2} ]
Segment2 [ {x1,y1}, {x2,y2} ]
I need to write a small algorithm in python to detect if the 2 lines are intersecting.
Update:
How can I check if 2 segments intersect?
I've the following data:
Segment1 [ {x1,y1}, {x2,y2} ]
Segment2 [ {x1,y1}, {x2,y2} ]
I need to write a small algorithm in python to detect if the 2 lines are intersecting.
Update:
Calculate the intersection point of the lines laying on your segments (it means basically to solve a linear equation system), then check whether is it between the starting and ending points of your segments.
The equation of a line is:
For a segment, it is exactly the same, except that x is included on an interval I.
If you have two segments, defined as follow:
The abcisse Xa of the potential point of intersection (Xa,Ya) must be contained in both interval I1 and I2, defined as follow :
And we could say that Xa is included into :
Now, we need to check that this interval Ia exists :
So, we have two line formula, and a mutual interval. Your line formulas are:
As we got two points by segment, we are able to determine A1, A2, b1 and b2:
If the segments are parallel, then A1 == A2 :
A point (Xa,Ya) standing on both line must verify both formulas f1 and f2:
The last thing to do is check that Xa is included into Ia:
In addition to this, you may check at startup that two of the four provided points are not equals to avoid all that testing.
if your data define line you just have to prove that they are not parallel. To do this you can compute
If this coefficient is equal for both Line1 and Line2, it means the line are parallel. If not, it means they will intersect.
If they are parallel you then have to prove that they are not the same. For that, you compute
If beta is the same for Line1 and Line2,it means you line intersect as they are equal
If they are segment, you still have to compute alpha and beta as described above for each Line. Then you have to check that (beta1 - beta2) / (alpha1 - alpha2) is greater than Min(x1_line1, x2_line1) and less than Max(x1_line1, x2_line1)
I thought I'd contribute a nice Swift solution:
Here is C code to check if two points are on the opposite sides of the line segment. Using this code you can check if two segments intersect as well.
}
Resolved but still why not with python... :)
This:
Output:
And this:
Output: