向鼠标移动一个点

Move a point toward the mouse

(我正在为此使用处理,但不一定相关。)

I'm looking for an algorithm that would take the point A and the point B (B being the mouse cursor position) and use them so that every frame the point A moves a little bit towards B (from -1px to 1px left/right up/down)

我试过 x1 += cos(atan((mouseY-y1)/(mouseX-x1))) 和 y1 的 sin 一样,但我没有似乎有效。

如果有人有想法,我将不胜感激。

不是寻找可以完成这项工作的内置函数,我想了解它背后的数学原理。

感谢您的宝贵时间。

重要的是点坐标是浮点值:

float x = 0.0, y= 0.0;

对于点的移动计算,我推荐使用PVector

设置 2 个向量,用于点和鼠标位置:

PVector Pt = new PVector(x, y);
PVector Pm = new PVector(mouseX, mouseY);

计算 Unit vectorPtPm:

PVector D = PVector.sub(Pm, Pt);
D.normalize();

通过newPt = Pt + D * min(speed, dist)计算新的点,但确保点移动不超过Euclidean distance到鼠标:

float speed = 3;
float movelen = min(PVector.dist(Pt, Pm), speed);
PVector newPt = PVector.add(Pt, D.mult(movelen));

同样可以通过算术运算实现

float dx = mouseX - x;
float dy = mouseY - y;
float dist = sqrt(dx*dx + dy*dy);
if (dist > 0) {
    float movelen = min(dist, speed);
    x += dx/dist * movelen;
    y += dy/dist * movelen;
}

(dx,dy) 是点到鼠标的向量,dist 是两点之间的 Euclidean distance。一个Unit vector可以用一个向量除以它的大小来计算,所以(dx/dist,dy/dist)是单位方向向量。 最后 (dx/dist * movelen, dx/dist * movelen) 与 D * movelen.

相同

看例子:
(该代码适用于任何 speed,甚至低于 1.0)

float x = 0.0, y= 0.0;

void setup() {
    size(300, 300);
    x = (float)random(width);
    y = (float)random(height);
}

void draw() {
    float speed = 3;

    /*
    //setup points
    PVector Pt = new PVector(x, y);
    PVector Pm = new PVector(mouseX, mouseY);

    // calcualte normalized direction
    PVector D = PVector.sub(Pm, Pt);
    D.normalize();

    // calcualte new point
    float movelen = min(PVector.dist(Pt, Pm), speed);
    PVector newPt = PVector.add(Pt, D.mult(movelen));
    x = newPt.x;
    y = newPt.y;
    */

    float dx = mouseX - x;
    float dy = mouseY - y;
    float dist = sqrt(dx*dx + dy*dy);
    if (dist > 0) {
        float movelen = min(dist, speed);
        x += dx/dist * movelen;
        y += dy/dist * movelen;
    }

    background(196);
    stroke(0);
    fill(255, 0, 0);
    ellipse((int)x, (int)y, 10, 10);
    fill(0, 255, 0);
    ellipse(mouseX, mouseY, 10, 10);
}