We want to determine if two line segments, and , intersect and if they do intersect, the point of intersection. First we analyze the problem. Case five in the list below is difficult to analyze which is why we leave it to the end.
- The segments are not parallel (easy)
- The segments are parallel and do not intersect (easy)
- The segments are collinear and do not intersect (easy)
- The segments are collinear and do intersect (easy)
- The segments are nearly parallel or nearly collinear (hard)
In this post I handle cases one through four. I leave case five for later posts.
For the problem setup let segment 1 be given by
where and p, r are 2d vectors, similarly let segment 2 be given by
where and q, s are 2d vectors.
This representation of the line segments yields a very natural method for computing their intersection.
Computing cross products is the heart of the algorithm for determining intersections. The two dimensional cross product of is given by
If the cross product is zero then the two vectors are collinear that is pointing in either the same direction or in opposite directions.
The two lines intersect when , by crossing both sides with we get
From this we solve for obtaining
We can similarly solve for , obtaining
If both t and u are between 0 and 1, then the two line segments intersect and the intersection point is given by where the value of t is the one we solved for. If either t or u are not between 0 and 1 then the line segments do not intersect.
But suppose , then we can’t solve for t and u. This is because means that r and s are parallel which means the two line segments are parallel. Please also note that implies that and are scalar multiplies of each other. If then the segments are parallel but not collinear hence they do not intersect. If then the segments are collinear and we can simply project both of them onto to x-axis and determine if their projections intersect.
For case 5 when is close to zero the analysis needs to be well thought out and I’ll leave it to future posts.
Credit Gareth Rees for his post at stackoverflow.com which is based on the method for 3D line intersection algorithm from the article “Intersection of two lines in three-space” by Ronald Graham, published in Graphics Gems, page 304.