Thursday, February 11, 2016

Finding the Intersection of Lines

The classical y = m*x+n line equation fails when finding intersections with vertical lines. Normally, the intersection point of two lines is found as follows:

Y = m1*x+n1 = m2*x+n2 --> x = (n2-n1)/(m1-m2)

Consider the following example, which clearly has an intersection at x = 1 and y = 0.5:

The classical equation for line AB results in m1 = infinity and n1 = -infinity, and for CD results in m2 = 0.5, n2 = 0. When you plug these values into x = (n2-n1)/(m1- m2), you get x = (0 - (-infinity)) / (infinity - 0.5) = infinity/infinity = NaN.

You could try to solve this problem using a bunch of if statements to check if a line is vertical, horizontal etc which would be prone to bugs. Or you could use parametric line equations:

Applying the above parametric formula to our example problem, we obtain the following equations:

Line1: P1 = A + (B - A) * t
Line2: P2 = C + (D - C) * u

To find the intersection point we equate P1 to P2:

A + (B - A) * t  = C + (D - C) * u.

Using scalar components:
Ax + (Bx-Ax)*t = Cx + (Dx-Cx)*u --> Ax-Cx = (Ax-Bx)*t + (Dx-Cx)*t
Ay + (By-Ay)*t = Cy + (Dy-Cy)*u --> Ay-Cy = (Ay-By)*t + (Dy-Cy)*t

Rearranging into matrix form:

| Ax-Bx, Dx-Cx | |t|  = |Ax-Cx|
| Ay-By, Dy-Cy | |u| = |Ay-Cy|

We can solve this M*TU = K system and obtain t and u values: TU = M^-1*K. t and u are -0.25 and 0.5 respectively. Finally to get intersection x,y coordinates, we can use

xIntersect = Ax + (Bx-Ax)*t
yIntersect = Ay + (By-Ay)*t

Which gives us the correct result of (1, 0.5)

An additional benefit of the parametric line equation is that it can easily be extended to three dimensional space. It is also used in calculating intersection lines with a planes.

Lesson learnt: Don't use y = m*x+n, instead use P = A + (B - A) * t

No comments: