get closest point to a line

后端 未结 12 1985
逝去的感伤
逝去的感伤 2020-11-28 04:45

I\'d like to have a straight forward C# function to get a closest point (from a point P) to a line-segment, AB. An abstract function may look like this. I\'ve search through

12条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 04:53

    Your point (X) will be a linear combination of points A and B:

    X = k A + (1-k) B
    

    For X to be actually on the line segment, the parameter k must be between 0 and 1, inclusive. You can compute k as follows:

    k_raw = (P-B).(A-B)  /  (A-B).(A-B)
    

    (where the period denotes the dot product)

    Then, to make sure the point is actually on the line segment:

    if k_raw < 0:
        k= 0
    elif k_raw > 1:
        k= 1
    else:
        k= k_raw
    

提交回复
热议问题