Calculating the Intersection between Two Lines


The common algebraic formula for defining two lines gives:

y = k1*x + c1
y =  k2*x + c2
At their intersection point (if any), x and y of both lines are identical. Solving the two equations yields:

x = (c2 - c1)/(k1 - k2)
y = k1*(c2 - c1)/(k1 - k2) + c1
The denominator (k1 - k2) is zero when the slope parameters k1 and k2 are equal. This singularity is expected, since parallel lines do not have an intersection point. Another singularity occurs when one of the lines is vertical — it has an infinite slope. Such cases must be treated separately, which is a serious drawback with this algorithm.

Another way to define two lines is in terms of two fixed points ( (x1,y1) , (x2,y2) or (x3,y3) , (x4,y4) in this case) and a parameter (t1 or t2).

x = (x2 - x1)*t1 + x1 -infinity < t1 < +infinity
y = (y2 - y1)*t1 + y1 -infinity < t1 < +infinity

x = (x4 - x3)*t2 + x3 -infinity < t2 < +infinity
y = (y4 - y3)*t2 + y3 -infinity < t2 < +infinity
At the intersection point, x and y of both lines are again identical:

(x2 - x1)*t1 + x1 = (x4 - x3)*t2 + x3
(y2 - y1)*t1 + y1 = (y4 - y3)*t2 + y3
Solving these equations yields:

t2 = [(y3 - y1)(x2 - x1) - (x3 - x1)(y2 - y1)]/[(x4 - x3)(y2 - y1) - (y4 - y3)(x2 - x1)]
The denominator becomes zero when (x4 - x3) (y2 - y1) equals (y4 - y3) (x2 - x1). Vertical and horizontal lines will create zero terms in the denominator, but the whole expression will evaluate to zero only when the lines are parallel.

The intersection point can then be computed:

x = (x4 - x3)*t2 + x3
y = (y4 - y3)*t2 + y3