Skip to content

Instantly share code, notes, and snippets.

@lennerd
Created April 9, 2014 11:44
Show Gist options
  • Save lennerd/10259253 to your computer and use it in GitHub Desktop.
Save lennerd/10259253 to your computer and use it in GitHub Desktop.
Line to Point Distance in Processing.
void setup() {
size(800, 600);
background(255);
noLoop();
}
void draw() {
line(50, 50, 750, 550);
}
void mouseMoved() {
println(lineDistance(50, 50, 750, 550, mouseX, mouseY));
}
float lineDistance(int x1, int y1, int x2, int y2, int mX, int mY) {
PVector lineStart, lineEnd, mouse, projection, temp;
lineStart = new PVector(x1, y1);
lineEnd = new PVector(x2, y2);
mouse = new PVector(mX, mY);
temp = PVector.sub(lineEnd, lineStart);
float lineLength = temp.x * temp.x + temp.y * temp.y; //lineStart.dist(lineEnd);
if (lineLength == 0F) {
return mouse.dist(lineStart);
}
float t = PVector.dot(PVector.sub(mouse, lineStart), temp) / lineLength;
if (t < 0F) {
return mouse.dist(lineStart);
}
if (t > lineLength) {
return mouse.dist(lineEnd);
}
projection = PVector.add(lineStart, PVector.mult(temp, t));
return mouse.dist(projection);
}
@vincentdiks
Copy link

t > lineLength should be t > 1, as t is a magnitude of the line vector and is not within the scope of lineLength

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment