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
检查速度超低时的子句。
推荐阅读
- blockchain - NEAR cli 合约调用有效,但从具有相同参数的 js sdk 调用时失败
- javascript - 如何从javascript中的URI中提取文件名?
- snowflake-cloud-data-platform - 插入行时生成时间戳
- javascript - 如何避免 D3.js 中的圆圈重叠
- python - Python:如何将系统发育树转换为循环格式?
- php - PHP 启动:无法在 Yii2 中加载动态库 '/usr/lib/php/20151012/pgsq
- javascript - axios 获取请求返回错误 UNDEFINED
- ansible - ansible - 使用 ipmath 将 1 添加到 ip 地址变量
- azure - 有没有办法通过 ARM 模板将加密(CMK-客户托管密钥)和 Vnet 集成添加到 Azure 语音服务(认知)
- spring - 一次测试多个 Spring Boot 服务