I need a basic function to find the shortest distance between a point and a line segment. Feel free to write the solution in any language you want; I can translate it into what I'm using (Javascript).
EDIT: My line segment is defined by two endpoints. So my line segment AB
is defined by the two points A (x1,y1)
and B (x2,y2)
. I'm trying to find the distance between this line segment and a point C (x3,y3)
. My geometry skills are rusty, so the examples I've seen are confusing, I'm sorry to admit.
Eli, the code you've settled on is incorrect. A point near the line on which the segment lies but far off one end of the segment would be incorrectly judged near the segment.Update: The incorrect answer mentioned is no longer the accepted one.Here's some correct code, in C++. It presumes a class 2D-vector
class vec2 {float x,y;}
, essentially, with operators to add, subract, scale, etc, and a distance and dot product function (i.e.x1 x2 + y1 y2
).EDIT: I needed a Javascript implementation, so here it is, with no dependencies (or comments, but it's a direct port of the above). Points are represented as objects with
x
andy
attributes.EDIT 2: I needed a Java version, but more important, I needed it in 3d instead of 2d.
One line solution using arctangents:
The idea is to move A to (0, 0) and rotate triangle clockwise to make C lay on X axis, when this happen, By will be the distance.
C#
One line C# (to be converted to SQL)
Matlab code, with built-in "self test" if they call the function with no arguments:
AutoHotkeys version based on Joshua's Javascript:
Didn't see a Java implementation here, so I translated the Javascript function from the accepted answer to Java code:
Couldn't resist coding it in python :)
Ditto for fortran :)