翻译对象、停止和继续-处理

Translate object, stopping, and continuing- Processing

我正在尝试将一个对象(我们的目的是矩形)从点 A 移动到 D。但是,在移动过程中我想在不同的部分停止运动并等待一段时间。

比如我想从A移动到B,等待5秒,然后从B移动到C,等待2秒。最后从C移到D。

我已经尝试了几件事。首先,我通过给它一个 "speed" (xspeed) 并通过 xspeed 增加它的位置 (xpos) 来移动我的对象。然后使用 if 语句,当它达到 100 时我停止了位置。然后我数了 5 秒并再次开始运动。然而,由于运动开始超过 x 位置 100,if 语句不允许我向前移动。我不知道我是否可以覆盖这个 if 语句。下面是我所做的代码:

  class Pipe {
  color c;
  float xpos;
  float ypos;
  float xspeed;
  int time;

  Pipe(color c_, float xpos_, float ypos_, float xspeed_) {
    c = c_;
    xpos = xpos_;
    ypos = ypos_;
    xspeed = xspeed_;
  }

  void display() {
    noStroke();
    fill(c);
    rectMode(CENTER);
    rect(xpos,ypos,10,200);
  }


  void pipeMove() {
    xpos = xpos + xspeed;
    if (xpos > 100) {
      xpos = 100;
      if (millis() > time) {
        time = millis()+5000;
        xpos = xpos + xspeed;
      }
    }
  }
}

Pipe myPipe1;
Pipe myPipe2;

void setup() {
  size(1500,500);
  myPipe1 = new Pipe(color(85,85,85),0,height/2,2);
//  myPipe2 = new Pipe(color(85,85,85),-100,height/2,2);
}

void draw() {
  background(255);
  myPipe1.display();
  myPipe1.pipeMove();
//  myPipe2.display();
//  myPipe2.pipeMove();
}

我尝试的另一个选项是使用 noLoop() 停止 Processing 中的自动循环,并在我的 class 中循环位置。但是,这不会移动我的对象。请参阅下面我的 for 循环代码。

class Pipe {
  color c;
  float xpos;
  float ypos;
  float xspeed;
  int time;

  Pipe(color c_, float xpos_, float ypos_, float xspeed_) {
    c = c_;
    xpos = xpos_;
    ypos = ypos_;
    xspeed = xspeed_;
  }

  void display() {
    noStroke();
    fill(c);
    rectMode(CENTER);
    rect(xpos,ypos,10,200);
  }


  void pipeMove() {
    for (int i = 0; i<100; i = i+1) {
    xpos = xpos + i;
    }
  }
}

我认为您的第一种方法是正确的。您已经完成了第一部分,现在您只需添加其他步骤。解决此问题的一种方法可能是在 Pipe class.

中使用 states

我的意思是,您只需跟踪管道当前在哪一步,然后根据您在哪一步做正确的事情。最简单的方法可能是将布尔值添加到 Pipe class:

class Pipe {
  color c;
  float xpos;
  float ypos;
  float xspeed;
  int time;

  boolean movingToA = true;
  boolean waitingAtA = false;
  boolean movingToB = false;
  //...

然后在你的 pipeMove() 函数中,根据你所处的状态做正确的事情,改变状态来改变行为:

  void pipeMove() {

    if (movingToA) {

      xpos = xpos + xspeed;

      if (xpos > 100) {
        xpos = 100;
        movingToA = false;
        waitingAtA = true;
        time = millis();
      }
    } else if (waitingAtA) {
      if (millis() > time + 5000) {
        waitingAtA = false;
        movingToB = true;
      }
    } else if (movingToB) {
      xpos = xpos + xspeed;

      if (xpos > 200) {
        xpos = 200;
        movingToB = false;
      }
    }
  }
}

这里有一些非常明显的改进 - 例如,您可以使用枚举值或潜在操作的数据结构,或参数化行为。但基本原理是相同的:根据您所处的状态执行不同的操作,然后更改该状态以更改行为。