Skip to content

Instantly share code, notes, and snippets.

@trpfrog
Created May 9, 2021 18:38
Show Gist options
  • Save trpfrog/10ceaefc0e7fa67baf9a534252ece61b to your computer and use it in GitHub Desktop.
Save trpfrog/10ceaefc0e7fa67baf9a534252ece61b to your computer and use it in GitHub Desktop.
最も近い半直線上の点の座標を計算するやつ
PVector A, B;
void halfStraightLine(float x1, float y1, float x2, float y2) {
final int INF = 10000;
line(x1, y1, x1 + (x2 - x1) * INF, y1 + (y2 - y1) * INF);
}
PVector calcQ(float x, float y) {
float theta = atan2(B.y - A.y, B.x - A.x);
float d = dist(A.x, A.y, B.x, B.y);
float s = (cos(theta) * (x - A.x) + sin(theta) * (y - A.y)) / d;
x = A.x + Math.max(0, s) * (B.x - A.x);
y = A.y + Math.max(0, s) * (B.y - A.y);
return new PVector(x, y);
}
void setup() {
size(300, 400);
A = new PVector(100, 100);
B = new PVector(200, 300);
}
void draw() {
background(245);
stroke(0);
halfStraightLine(A.x, A.y, B.x, B.y);
noStroke();
final PVector p = new PVector(mouseX, mouseY);
final PVector q = calcQ(p.x, p.y);
final int r = 10;
textSize(16);
fill(200);
text("A", A.x + r, A.y + r);
text("B", B.x + r, B.y + r);
ellipse(A.x, A.y, r, r);
ellipse(B.x, B.y, r, r);
fill(0);
text("P", p.x + r, p.y + r);
text("Q", q.x + r, q.y + r);
fill(#dbbb92);
ellipse(p.x, p.y, r, r);
fill(#90e200);
ellipse(q.x, q.y, r, r);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment