处理 3.3.7 draw() 停止循环

Processing 3.3.7 draw() stops looping

我在 Processing 3.3.7 上写了这段代码,它创建了一个弹跳的球。

Ball b;

int n = 0;

void setup() {
  size(600, 400);

  b = new BallBuilder()
          .buildRadius(20)
          .buildXSpeed(5)
          .buildYSpeed(5)
          .buildYAcceleration(1)
          .toBall();
}

void draw() {
  background(0);
  n++;
  print("n: " + n + " | ");
  print("xSpeed: " + b.getXSpeed() + " | ");
  println("ySpeed: " + b.getYSpeed());

  b.display();
  b.move();
}

还有一个球class,它有这些方法:

  void display() {
    fill(255);
    stroke(255);
    ellipse(xPosition, yPosition, radius * 2, radius * 2);
  }

  void move() {
    this.moveX();
    this.moveY();
  }

  private void moveX() {
    for(float i = 0; i <= abs(this.xSpeed); i += abs(this.xSpeed) / 10) {
      this.bounceX();
      this.xPosition += this.xSpeed / 10;
    }
  }

  private void moveY() {
    for(float i = 0; i <= abs(this.ySpeed); i += abs(this.ySpeed) / 10) {
      this.bounceY();
      this.yPosition += this.ySpeed / 10;
    }

    this.ySpeed += this.yAcceleration;
  }

  void bounceX() {
    if(!this.canMoveX()) {
      this.xSpeed = -this.xSpeed;
    }
  }

  void bounceY() {
    if(!this.canMoveY()) {
      this.ySpeed = -this.ySpeed;
    }
  }

  boolean canMoveX() {
    if(this.xPosition < radius || this.xPosition >= width - this.radius) {
      return false;
    }

    return true;
  }

  boolean canMoveY() {
    if(this.yPosition < radius || this.yPosition >= height - this.radius) {
      return false;
    }

    return true;
  }
}

还有一个生成器和两个 Ball 吸气器(这里没有张贴,因为它们非常简单)。问题是,xSpeed 和 ySpeed 都不能设置为 0,否则代码停止 运行。这意味着我需要在实例化时给它两个速度,如果我设置加速度使速度变为 0,程序停止 运行(n 变量用于计算draw() 循环,当速度达到 0 时,它停止增加)。我错过了什么?

您是否尝试过 debugging your code 找出代码与您预期的不同之处?

你有两个这样的循环:

for(float i = 0; i <= abs(this.xSpeed); i += abs(this.xSpeed) / 10) {

您可以在这些循环中添加打印语句,如下所示:

println("i: " + i);

如果这样做,您会发现 i 始终是 0。这是为什么?

想想如果this.xSpeed0会发生什么:这个循环什么时候退出?