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
xandyattributes.EDIT 2: I needed a Java version, but more important, I needed it in 3d instead of 2d.
Here, in the function parameters,
<px,py,pz>is the point in question and the line segment has the endpoints<lx1,ly1,lz1>and<lx2,ly2,lz2>. The functiondist_sq(which is assumed to exist) finds the square of the distance between two points.