Treat the lines as parametric where line 1 is:
X = x11 + dx1 * t1
Y = y11 + dy1 * t1
and line 2 is:
X = x21 + dx2 * t2
Y = y21 + dy2 * t2
Setting these equal gives:
x11 + dx1 * t1 = x21 + dx2 * t2
y11 + dy1 * t1 = y21 + dy2 * t2
Rearranging:
x11 - x21 + dx1 * t1 = dx2 * t2
y11 - y21 + dy1 * t1 = dy2 * t2
(x11 - x21 + dx1 * t1) * dy2 = dx2 * t2 * dy2
(y11 - y21 + dy1 * t1) * (-dx2) = dy2 * t2 * (-dx2)
Adding the equations gives:
(x11 - x21) * dy2 + ( dx1 * dy2) * t1 +
(y21 - y11) * dx2 + (-dy1 * dx2) * t1 = 0
Solving for t1 gives:
t1 * (dy1 * dx2 - dx1 * dy2) =
(x11 - x21) * dy2 + (y21 - y11) * dx2
t1 = ((x11 - x21) * dy2 + (y21 - y11) * dx2) /
(dy1 * dx2 - dx1 * dy2)
Similarly solve for t2.
Notes:
- If 0 ≤ t1 ≤ 1, then the point lies on segment 1.
- If 0 ≤ t2 ≤ 1, then the point lies on segment 1.
- If dy1 * dx2 - dx1 * dy2 = 0 then the lines are parallel.
- If the point of intersection is not on both segments, then this is almost certainly not the point where the two segments are closest.
|