我的加工草图中有一个线段和一个圆。我希望圆的中心点q在线段上找到最接近的点p,圆将朝着它移动。
我不太确定该如何编码(在处理中),因此任何建议都很棒!谢谢!
到目前为止,这是我的代码:
int xPos1 = 200;
int yPos1 = 200;
int xp1 = 50;
int yp1 = 50;
int xp2 = 350;
int yp2 = 50;
void setup() {
size(400, 400);
strokeWeight(2);
line(xp1, yp1, xp2, yp2);
strokeWeight(1);
}
void draw() {
drawCircle();
}
void drawCircle() {
fill(50, 120, 120);
//circle
ellipse(xPos1, yPos1, 75, 75);
//circle center
ellipse(xPos1, yPos1, 7, 7);
fill(255);
text("Q", xPos1 + 15, yPos1 + 5);
fill(50, 120, 120);
}
最佳答案
点在直线上的投影如下:
从x = a + t * n形式的直线和点p开始。
表示距点p的直线上最近的点的向量分量为:
(a-p)-((a-p)点n)n
所以我们有:p +(a-p)-((a-p)点n)n
经过一些简化,我们得到:
a-(((a-p)点n)n
请注意,((a-p)点n)n是向量分量,代表沿线从最近点到起点(即从最近点到p到a)的位置
让我们使用PVector
使生活更轻松一些。
PVector p = new PVector(200, 200);
PVector a = new PVector(50, 50);
PVector b = new PVector(350, 50);
PVector n = new PVector(350, 50); // |p2 - p1|
void setup() {
size(400, 400);
strokeWeight(2);
strokeWeight(1);
// initialize our normalized (unit length) line direction
n.sub(a);
n.normalize();
}
void draw() {
drawCircle();
}
PVector getNearestPointOnLine(PVector p, PVector a, PVector n){
// the notation turns the computation inside out,
// but this is equivalent to the above equation
PVector q = PVector.mult(n, -PVector.sub(a, p).dot(n));
q.add(a);
return q;
}
void drawCircle() {
// lets draw everything here where we can see it
background(255, 255, 255);
line(a.x, a.y, b.x, b.y);
fill(50, 120, 120);
//circle
// NOTE: this may require hooking up a mouse move event handler
p.x = mouseX;
p.y = mouseY;
PVector q = getNearestPointOnLine(p, a, n);
ellipse(q.x, q.y, 75, 75);
//circle center
ellipse(q.x, q.y, 7, 7);
fill(0); // make text visible on white background
text("Q", q.x + 15, q.y + 5);
//fill(50, 120, 120);
}
参考:https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Vector_formulation