问题描述
这是我编写的一小段代码,用于在 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
,但下一次通过循环时会添加 {{1} } 到 gravity
,然后 speed
到 speed
,使 y
再次大于 y
(略大于 1 像素)。这使得球在零高度跳跃的无限循环中上下跳跃。
您可以对反射速度使用阈值。如果低于阈值,则停止循环。
在文件的顶部,添加一行
height - 25
然后在 float threshold = 0.5; //experiment with this
中,就在该行之后
draw()
添加行
speed = speed * (-1 * efficiency);
在这种情况下,您可以丢弃检查速度何时超低的 if(abs(speed) < threshold) noLoop();
子句。