这是我编写的一些小代码,用于在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
,第二天一次循环增加gravity
至speed
再speed
至y
,使得y
大于height - 25
(按略多于1个像素以上)一次。这使球可以通过零高度的无限跳来回跳动。
您可以对反射速度使用阈值。如果低于阈值,则停止循环。
在文件顶部,添加一行
float threshold = 0.5; //experiment with this
然后draw()
在行后
speed = speed * (-1 * efficiency);
添加线
if(abs(speed) < threshold) noLoop();
在这种情况下,您可以丢弃if
检查速度何时超低的子句。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句