Java/Processing - 从一个节点到另一个节点以偶数行移动 object

Java/Processing - Moving object in an even line from node to node

我的标题可能没有多大意义,这就是为什么我在谷歌搜索我的问题时遇到了一些问题。

我正在尝试将屏幕上的形状从一组 X/Y 坐标直线移动到另一组坐标。 例如,

这是class设置新目标方向的方法。

void setTargetPosition(int targetX, int targetY) {
    xTar = targetX;
    yTar = targetY;
        
    if (xPos > xTar) 
        xDir = -1; 
    else
        xDir = 1;
        
    if (yPos > yTar)
        yDir = -1; 
    else
        xDir = 1;
}

这将设置 X/Y 变量的方向,以下代码将在屏幕上移动播放器。

void drawPlayer() {
        
    fill(circleColour);
    circle(xPos,yPos,35);

    //stops player from moving once target destination has been reached
    if (xPos == xTar) 
        xDir = 0; 
        
    if (yPos == yTar)
        yDir = 0;
        
    xPos += xDir;
    yPos += yDir;
}

上面的代码大部分都按预期工作,但我需要找到一种方法来按比例更改 X/Y 坐标,使其更接近 'direct line' 到目的地。

抱歉,如果这没有意义。我不知道使用正确的术语。

您必须使用浮点值而不是整数值来计算移动:

float xTar;
float yTar;
float xPos;
float yPos;

setTargetPosition 只需设置 xTaryTar:

void setTargetPosition(float targetX, float targetY) {
    xTar = targetX;
    yTar = targetY;
}

drawPlayer中你必须计算从对象位置到目标的方向向量(PVector):

PVector dir = new PVector(xTar - xPos, yTar - yPos);

如果向量的长度 (mag()) 大于 0,则必须移动对象:

if (dir.mag() > 0.0) {
    // [...]
}

如果必须移动对象,则计算Unit vector by normalize(). Note, the length of a unit vector is 1. Multiply the vector by a certain speed by mult()。这会将向量缩放到一定长度。确保向量的长度不大于到对象的距离 (min(speed, dir.mag()))。最后将vector的分量添加到object的位置:

dir.normalize();
dir.mult(min(speed, dir.mag()));

xPos += dir.x;
yPos += dir.y;

看例子:

class Player {
  
    float xTar;
    float yTar;
    float xPos;
    float yPos;
    color circleColour = color(255, 0, 0);
    
    Player(float x, float y)
    {
      xTar = xPos = x;
      yTar = yPos = y;
    }
  
    void setTargetPosition(float targetX, float targetY) {
        xTar = targetX;
        yTar = targetY;
    }
    
    void drawPlayer() {
    
        fill(circleColour);
        circle(xPos,yPos,35);
    
        float speed = 2.0;    
        PVector dir = new PVector(xTar - xPos, yTar - yPos);
        
        if (dir.mag() > 0.0) {
            dir.normalize();
            dir.mult(min(speed, dir.mag()));
            
            xPos += dir.x;
            yPos += dir.y;
        }
    }
}

Player player;

void setup() {

   size(500, 500);
   player = new Player(width/2, height/2);
}

void draw() {
    background(255);
    player.drawPlayer();
}

void mousePressed() {
    player.setTargetPosition(mouseX, mouseY);
}