Skip to content

Instantly share code, notes, and snippets.

@tmshv
Created April 22, 2013 20:40
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 tmshv/5438343 to your computer and use it in GitHub Desktop.
Save tmshv/5438343 to your computer and use it in GitHub Desktop.
how to project vertex on line
PVector v1;
PVector v2;
void setup() {
size(500, 500);
ellipseMode(CENTER);
textSize(12);
v1 = new PVector(random(width), random(height));
v2 = new PVector(random(width), random(height));
}
void draw(){
background(204);
PVector mouse = mouseCoord();
PVector projection = project(mouse, v1, v2);
line(v1.x, v1.y, v2.x, v2.y);
line(mouse.x, mouse.y, projection.x, projection.y);
drawVertex(projection, 10, color(200, 0, 0), "projection");
drawVertex(v1, 4, color(255, 255, 255), "first");
drawVertex(v2, 4, color(255, 255, 255), "second");
text("dist:"+dist(mouse.x, mouse.y, projection.x, projection.y), mouse.x, mouse.y);
drawComment();
}
void drawVertex(PVector vertex, int size, color c, String message){
fill(c);
ellipse(vertex.x, vertex.y, size, size);
text(message, vertex.x+5, vertex.y);
}
void drawComment(){
String message = "> click left => specifying first vertex of line;\n";
message += "> click right => specifying second vertex of line;\n";
message += "> red circle is projection of mouse pointer on line(first, second);\n";
text(message, 5, 10);
}
PVector mouseCoord(){
return new PVector(mouseX, mouseY);
}
void mousePressed(){
if(mouseButton == LEFT) v1 = mouseCoord();
else v2 = mouseCoord();
}
PVector project(PVector vertex, PVector lineVertex1, PVector lineVertex2) {
PVector a = new PVector(vertex.x - lineVertex1.x, vertex.y - lineVertex1.y);
PVector b = new PVector(lineVertex2.x - lineVertex1.x, lineVertex2.y - lineVertex1.y);
//Формула проецирования вектора a на вектор b:
float dot_product = (a.x * b.x + a.y * b.y);
float b_length_quad = b.x * b.x + b.y * b.y;
PVector p = new PVector(
( dot_product / b_length_quad ) * b.x,
( dot_product / b_length_quad ) * b.y
);
return new PVector(
lineVertex1.x + p.x,
lineVertex1.y + p.y
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment