Perpendicular (nearest) distance from a point to a line in 2D

Calculating the perpendicular distance from a point to a line in 2D is useful, when you want to find out what the nearest (i.e. closest or shortest) distance is from that point, to the line. Here is the formula:

given lineStartPoint { X, Y } -> the line's start point in 2D space
given lineEndPoint { X, Y } -> the line's end point in 2D space
given point { X, Y } -> the point in 2D space whose nearest distance should be calculated

neartestDistance =
    Abs(
        (lineEndPoint.Y - lineStartPoint.Y) * point.X
      - (lineEndPoint.X - lineStartPoint.X) * point.Y
      + lineEndPoint.X * lineStartPoint.Y
      - lineEndPoint.Y * lineStartPoint.X
    )
    /
    Sqrt(
        (lineEndPoint.Y - lineStartPoint.Y)
      * (lineEndPoint.Y - lineStartPoint.Y)
      + (lineEndPoint.X - lineStartPoint.X)
      * (lineEndPoint.X - lineStartPoint.X)
    )

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *