Perpendicular on a line from a given point

前端 未结 14 1659
名媛妹妹
名媛妹妹 2020-11-29 18:34

How can I draw a perpendicular on a line segment from a given point? My line segment is defined as (x1, y1), (x2, y2), If I draw a perpendicular from a point (x3,y3) and it

14条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 19:06

    I agree with peter.murray.rust, vectors make the solution clearer:

    // first convert line to normalized unit vector
    double dx = x2 - x1;
    double dy = y2 - y1;
    double mag = sqrt(dx*dx + dy*dy);
    dx /= mag;
    dy /= mag;
    
    // translate the point and get the dot product
    double lambda = (dx * (x3 - x1)) + (dy * (y3 - y1));
    x4 = (dx * lambda) + x1;
    y4 = (dy * lambda) + y1;
    

提交回复
热议问题