Created
October 29, 2011 20:00
-
-
Save atduskgreg/1325002 to your computer and use it in GitHub Desktop.
Find the distance from a polygon using the Bourke line-distance algorithm for each segment. Example of it in action here: http://itp.nyu.edu/~gab305/files/gif_with_blurred_borders.gif
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// example of this in action here: http://itp.nyu.edu/~gab305/files/gif_with_blurred_borders.gif | |
float testApp::distanceFromLine(const ofPoint & p, const ofPoint & l1, const ofPoint & l2){ | |
float xDelta = l2.x - l1.x; | |
float yDelta = l2.y - l1.y; | |
// final double u = ((p3.getX() - p1.getX()) * xDelta + (p3.getY() - p1.getY()) * yDelta) / (xDelta * xDelta + yDelta * yDelta); | |
float u = ((p.x - l1.x) * xDelta + (p.y - l1.y)*yDelta) / (xDelta * xDelta + yDelta * yDelta); | |
ofPoint closestPointOnLine; | |
if (u < 0) { | |
closestPointOnLine = l1; | |
} else if (u > 1) { | |
closestPointOnLine = l2; | |
} else { | |
closestPointOnLine = ofPoint(l1.x + u * xDelta, l1.y + u * yDelta); | |
} | |
ofPoint d = p - closestPointOnLine; | |
return sqrt(d.x * d.x + d.y * d.y); // distance | |
} | |
float testApp::distanceFromPoly(const ofPoint & p, const vector<ofPoint> & poly){ | |
float result = 10000; | |
// check each line | |
for(int i = 0; i < poly.size(); i++){ | |
int previousIndex = i -1; | |
if(previousIndex < 0){ | |
previousIndex = poly.size() - 1; | |
} | |
ofPoint currentPoint = poly.at(i); | |
ofPoint previousPoint = poly.at(previousIndex); | |
float segmentDistance = distanceFromLine(ofPoint(p.x,p.y), previousPoint, currentPoint); | |
if(segmentDistance < result){ | |
result = segmentDistance; | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Greg, there's no way you could write this in JavaScript? Or know where I can find a similar module? Kind Regards, Greg