Skip to content

Instantly share code, notes, and snippets.

@atduskgreg
Created October 29, 2011 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atduskgreg/1324876 to your computer and use it in GitHub Desktop.
Save atduskgreg/1324876 to your computer and use it in GitHub Desktop.
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 lineLength = sqrt((currentPoint.x - previousPoint.x)*(currentPoint.x - previousPoint.x) + (currentPoint.y - previousPoint.y)*(currentPoint.y - previousPoint.y));
float u = (((p.x - previousPoint.x) * (currentPoint.x - previousPoint.x)) +
((p.y - previousPoint.y) * (currentPoint.y - previousPoint.x))) / (lineLength * lineLength);
//ofVec2f pointVector = ofVec2f(p.x, p.y);
if( u < 0.0f || u > 1.0f )
continue;
ofVec2f intersection = ofVec2f();
intersection.x = previousPoint.x + u * (currentPoint.x - previousPoint.x);
intersection.y = previousPoint.y + u * (currentPoint.y - previousPoint.y);
float segmentDistance = intersection.length();
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