math - Function for finding the distance between a point and an edge in java -
does have function in java finding shortest distance between point , line segment/edge? every example find in language , uses bunch of sub functions. can't based on assumption perpendicular.
update
i ported on python function java. if @ math , can verify appreciate it. x , y point, , other params line segment.
public float pdistance(float x, float y, float x1, float y1, float x2, float y2) { float = x - x1; float b = y - y1; float c = x2 - x1; float d = y2 - y1; float dot = * c + b * d; float len_sq = c * c + d * d; float param = -1; if (len_sq != 0) //in case of 0 length line param = dot / len_sq; float xx, yy; if (param < 0) { xx = x1; yy = y1; } else if (param > 1) { xx = x2; yy = y2; } else { xx = x1 + param * c; yy = y1 + param * d; } float dx = x - xx; float dy = y - yy; return (float) math.sqrt(dx * dx + dy * dy); }
we can simplify things bit. don't need calculate param. can find vector v @ right angles line. take dot product of vector (a,b). in 2d easy enough find vector orthogonal (c,d), (-d,c).
public float pdistance(float x, float y, float x1, float y1, float x2, float y2) { float = x - x1; // position of point rel 1 end of line float b = y - y1; float c = x2 - x1; // vector along line float d = y2 - y1; float e = -d; // orthogonal vector float f = c; float dot = * e + b * f; float len_sq = e * e + f * f; return (float) math.abs(dot) / math.sqrt(len_sq); }
if worried performance can easier work squared distances last line be
return (float) dot * dot / len_sq;
this saves having calculate square root. if want calculate closest edge, find squared distances each edge , select smallest.
this function find distance infinite line rather line segment. may not want. solution in question differs in happens if point beyond 2 ends of line segment. there find distance closest end point.
Comments
Post a Comment