Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Animation to show how a distance of a point to a line segment looks. Ref: http://stackoverflow.com/a/1501725
PVector lineStart, lineEnd, point;
void setup() {
size(600, 600);
updatePoints();
}
void draw() {
background(0);
float d = distToSegment(lineStart, lineEnd, point);
stroke(255);
noFill();
line(lineStart.x, lineStart.y, lineEnd.x, lineEnd.y);
point(point.x, point.y);
ellipse(point.x, point.y, d * 2, d * 2);
updatePoints();
}
void updatePoints() {
float r = frameCount / 30.0;
lineStart = new PVector(cos(r), sin(r));
lineStart.mult(width / 10.0);
lineStart.add(100, 100);
lineEnd = new PVector(cos(r + HALF_PI), sin(r * 1.1 + HALF_PI));
lineEnd.mult(40);
lineEnd.add(500, 500);
if(mouseX == 0 && mouseY == 0) {
float r2 = frameCount / 40.0;
point = new PVector(cos(r2), sin(r2));
point.mult(width / 2.0);
point.add(width / 2.0, height / 2.0);
}
else {
point = new PVector(mouseX, mouseY);
}
}
float dist_squared(PVector a, PVector b) {
return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
}
float distToSegment(PVector v, PVector w, PVector p) {
float l2 = dist_squared(v, w);
if(l2 == 0.0) {
return PVector.dist(p, v);
}
float t = max(0, min(1, PVector.dot(p.copy().sub(v), w.copy().sub(v)) / l2));
PVector projection = v.copy().add(w.copy().sub(v).mult(t));
return PVector.dist(p, projection);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment