首页 > 解决方案 > 加工 | 如何阻止球改变它的颜色

问题描述

这是我编写的一个小代码,用于让球在处理中弹跳。球应该改变它从“地面”反弹的所有东西的颜色,变得越来越慢,最后落在地面上。但是——这就是我遇到的问题——球不会停止在底部改变它的颜色——这意味着它不会停止弹跳,对吧?

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

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

标签: processing

解决方案


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

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

在文件的顶部,添加一行

float threshold = 0.5; //experiment with this

然后在draw(),就在这条线之后

speed = speed * (-1 * efficiency);

添加行

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

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


推荐阅读