Created
April 9, 2014 11:44
-
-
Save lennerd/10259253 to your computer and use it in GitHub Desktop.
Line to Point Distance in Processing.
This file contains hidden or 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
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
t > lineLength should be t > 1, as t is a magnitude of the line vector and is not within the scope of lineLength