Search code examples
c++mathgeometry2d

Given perpendicular distance d on line1, how to find point P on line2 in C++?


Given line1, line2, and distance d, I want to write a program to calculate the point on Line2 that is perpendicular to Line1, and the perpendicular distance is d.

enter image description here

Does anyone know where to start? In C++ or any other programming language.

Thanks in advance.


Solution

  • Normalize line1 equation

    L = sqrt(a1*a1+b1*b1)
    a11 = a1 / L
    b11 = b1 / L
    c11 = c1 / L
    

    Now for arbitrary point (x,y) length of perpendicular projection onto line1 is

    d = a11*x + b11*y + c11
    a11*x + b11*y + (c11-d) = 0
    

    for vertical line2 case (b2==0) and (b11 != 0)

    x = c2/a2
    a11*c2/a2 + b11*y + (c11-d) = 0
    y = -(a11*c2/a2 + (c11-d)) / b11
    

    so needed point is (c2/a2, -(a11*c2/a2 + (c11-d)) / b11)

    For general case, if (a11*b2 != b11*a2) (non-parallel line case):

    y = - (a2*x + c2)/b2
    a11*x - b11*(a2*x+c2)/b2 + (c11-d) = 0
    a11*x - b11*a2*x/b2  + (c11 - d - b11*c2/b2) = 0
    x*(a11 - b11*a2/b2) =  (d + b11*c2/b2 - c11)
    x = (d + b11*c2/b2 - c11) / (a11 - b11*a2/b2)
    

    and point is ((d + b11*c2/b2 - c11) / (a11 - b11*a2/b2), y for this x)