It took me a suprisingly long time on a plane ride to figure a formula for the intersection point of two line segments
The general idea is to set up a system of parametric equations where t
ranges from 0 (output is the first endpoint of the segment) to 1 (output is the first endpoint of the segment)
x0 = x0:0 * (1 - t0) + x0:1 * t0
y0 = y0:0 * (1 - t0) + y0:1 * t0
x1 = x1:0 * (1 - t1) + x1:1 * t1
y1 = y1:0 * (1 - t1) + y1:1 * t1
Since we are solving for an intersection point, x0 = x1
and y0 = y1
.
Thus we end up with two equations each with two unknowns: t0
and t1
x0:0 * (1 - t0) + x0:1 * t0 = x1:0 * (1 - t1) + x1:1 * t1
y0:0 * (1 - t0) + y0:1 * t0 = y1:0 * (1 - t1) + y1:1 * t1
With a bit of algebra it is straightforward to solve for both variables. If they both exist in the range [0, 1]
, the segments intersect. Find the intersection point by substituting their values into the original equations.