加工 |如何阻止球改变颜色

Processing | How to stop the ball from changing it's color

这是我编写的一些代码,用于在 Processing 中使球弹跳。球应该改变它从“地面”反弹的所有颜色,并且变得越来越慢并最终落在地面上。 但是 - 这就是我遇到的问题 - 球不会停止改变底部的颜色 - 这意味着它不会停止弹跳,对吧?

问题是:如何让球停下来不再改变颜色?

float y = 0.0;
float speed = 0;
float efficiency = 0.9;
float gravitation = 1.3;


void setup(){
  
  size(400, 700);
  //makes everything smoother
  frameRate(60);
  //color of the ball at the beginning
  fill(255);
  
}

void draw() {
  
  // declare background here to get rid of thousands of copies of the ball
  background(0);
  
  //set speed of the ball
  speed = speed + gravitation;
  y = y + speed;
  
  //bouce off the edges
  if (y > (height-25)){
    //reverse the speed
    speed = speed * (-1 * efficiency);
    
    //change the color everytime it bounces off the ground
    fill(random(255), random(255), random(255));
  }
  
  //rescue ball from the ground
  if (y >= (height-25)){
    y = (height-25);
  }
 
/*
  // stop ball on the ground when veloctiy is super low
  if(speed < 0.1){
    speed = -0.1;
  }
*/
  
  // draw the ball
  stroke(0);
  ellipse(200, y, 50, 50);
  
}

问题是,即使您将速度设置为 -0.1(当它很小时),并将 y 设置为 height - 25,下一次循环会添加 gravityspeed 然后 speedy,再次使 y 大于 height - 25(略多于 1 个像素)。这使得球通过零高度跳跃的无限循环上下跳跃。

您可以对反射速度使用阈值。如果低于阈值,则停止循环。

在文件的顶部,添加一行

float threshold = 0.5; //experiment with this

然后在 draw() 行之后

speed = speed * (-1 * efficiency);

添加行

if(abs(speed) < threshold) noLoop();

在这种情况下,您可以丢弃检查速度何时超低的 if 子句。