代码之家  ›  专栏  ›  技术社区  ›  Fabio Luis

处理3.3.7 draw()停止循环

  •  1
  • Fabio Luis  · 技术社区  · 6 年前

    我在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 回复  |  直到 6 年前
        1
  •  0
  •   Kevin Workman    6 年前

    你试过了吗 debugging your code 找出代码与您预期的不同之处?

    有两个这样的循环:

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

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

    println("i: " + i);
    

    如果你这么做了,你会发现 i 总是 0 .为什么?

    想想如果 this.xSpeed 0 :这个循环什么时候退出?