Perpendicular on a line segment from a given point

后端 未结 9 1551
小鲜肉
小鲜肉 2020-12-02 11:52

I want to calculate a point on a given line that is perpendicular from a given point.

I have a line segment AB and have a point C outside line segment. I want to ca

9条回答
  •  死守一世寂寞
    2020-12-02 12:14

    There is a simple closed form solution for this (requiring no loops or approximations) using the vector dot product.

    Imagine your points as vectors where point A is at the origin (0,0) and all other points are referenced from it (you can easily transform your points to this reference frame by subtracting point A from every point).

    In this reference frame point D is simply the vector projection of point C on the vector B which is expressed as:

    // Per wikipedia this is more efficient than the standard (A . Bhat) * Bhat
    Vector projection = Vector.DotProduct(A, B) / Vector.DotProduct(B, B) * B
    

    The result vector can be transformed back to the original coordinate system by adding point A to it.

提交回复
热议问题