Java 加工过程中点到直线的正交投影?

Java 加工过程中点到直线的正交投影?,java,math,vector,processing,orthogonal,Java,Math,Vector,Processing,Orthogonal,我的加工草图中有一条线段和一个圆。我想要圆心,点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,

我的加工草图中有一条线段和一个圆。我想要圆心,点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)dotn)n

经过简化后,我们有: a-((a-p)点n)n


注意((a-p)点n)n是表示从最近点到起点(即从最近点到p再到a)的直线位置的矢量分量

让我们使用
PVector
s让生活变得更轻松

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);
}

参考:

请注意,点q仍将出现在线段两端之外,即此处没有“边界”检查。谢谢!这是非常有用的。不过我也在寻找一个圆,它朝着线段上最近的点移动。就像我们看到圆圈移动一样。任何关于如何做到这一点的想法都会很好!您可以使用相同的向量公式,其中t是0-1中的值,n是从球到最近点方向上的归一化向量(即,使用我们已有的变量的范数(q-p))。wikipedia的文章描述了每个向量组件,就像一个通过公式工作一样。:)例如,当t为0时,上述结果导致球位于点p,当t为1时,球将位于点q。如果您需要帮助了解如何在这种情况下设置球的动画,只需问另一个问题。在这里贴一个链接,如果你没有得到快速回复,我可以在下班后查看。