处理3.3.7 draw()停止循环

时间:2018-05-31 23:51:22

标签: processing draw

我在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();
}

还有一个Ball类,它有以下几种方法:

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

还有一个建造者和两个吸球者(不在这里发布,因为他们非常直接)。问题是,xSpeed和ySpeed都不能设置为0,否则代码会停止运行。这意味着我需要在实例化时给它两种速度,如果我设置加速使速度变为0,程序停止运行(n变量用于计算draw()循环的次数,当速度达到0时,它会停止增加)。我错过了什么?

1 个答案:

答案 0 :(得分:0)

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

你有两个这样的循环:

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

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

println("i: " + i);

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

考虑如果this.xSpeed0会发生什么:此循环何时退出?

相关问题