Find a line intersecting a known line at right angle, given a point

后端 未结 6 642
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 15:53

This is basic graphics geometry and/or trig, and I feel dumb for asking it, but I can\'t remember how this goes. So:

  1. I have a line defined by two points (x1, y1
6条回答
  •  南方客
    南方客 (楼主)
    2020-12-29 16:04

    You can find that point by considering first a generic point (x, y) along the line from (x1, y1) to (x2, y2):

    x = x1 + t*(x2 - x1)
    y = y1 + t*(y2 - y1)
    

    and the computing the (squared) distance from this point from (xp, yp)

    E = (x - xp)**2 + (y - yp)**2
    

    that substituting the definition of x and y gives

    E = (x1 + t*(x2 - x1) - xp)**2 +
        (y1 + t*(y2 - y1) - yp)**2
    

    then to find the minimum of this distance varying t we derive E with respect to t

    dE/dt = 2*(x1 + t*(x2 - x1) - xp)*(x2 - x1) +
            2*(y1 + t*(y2 - y1) - yp)*(y2 - y1)
    

    that after some computation gives

    dE/dt = 2*((x1 - xp)*(x2 - x1) + (y1 - yp)*(y2 - y1) +
               t*((x2 - x1)**2 + (y1 - y2)**2))
    

    looking for when this derivative is zero we get an explicit equation for t

    t = ((xp - x1)*(x2 - x1) + (yp - y1)*(y2 - y1)) /
        ((x2 - x1)**2 + (y2 - y1)**2)
    

    so the final point can be computed using that value for t in the definition of (x, y).

    Using vector notation this is exactly the same formula suggested by Gareth...

    t = 

    /

    where the notation represents the dot product operation ax*bx + ay*by.

    Note also that the very same formula works in an n-dimensional space.

提交回复
热议问题