英文:
How to make repeading 3D ball on Y coordinate in processing?
问题
以下是翻译好的内容:
我正在使用Processing制作动画。然后,我遇到了一个问题。我为您准备了一个简单的代码。同时,我认为这个问题对于初学者可能会有帮助。
PShape ball;
float ballSpeed = random(0.5, 1);
float ballSize = random(5, 10);
float x = 200, y = 300, z = 0;
void setup() {
size(400, 400, P3D);
noStroke(); // 这是为了"不看到球上的细节"
ball = createShape(SPHERE, ballSize);
}
void draw() {
background(0);
translate(x, y, z); // 旋转球体
println(y); // 检查y坐标
fill(255);
shape(ball);
y -= ballSpeed; // 球体可以向上移动
}
所以,我想为当球体到达100时创建一个条件,球体应该返回或开始它的初始位置,然后再次前往100。我尝试了许多条件,但无法解决它。如果您能帮助我,我会很高兴。谢谢。
英文:
I was making an animation on processing. Then, I confused about on a problem. I prepare a simple code for you. Also, I think the question can helpfull for the beginners.
PShape ball;
float ballSpeed = random(0.5, 1);
float ballSize = random(5, 10);
float x = 200, y = 300, z = 0;
void setup() {
size(400, 400, P3D);
noStroke(); // That's for "not see details on sphere"
ball = createShape(SPHERE, ballSize);
}
void draw() {
background(0);
translate(x, y, z); // rotate the ball
println(y); // checking the y coordinates
fill(255);
shape(ball);
y -= ballSpeed; // the ball can go to top
}
So, I want to make a condition for if the ball reach the 100, the ball should return or start its first position and then again it should go to 100 again. I tried many if conditions but couldn’t figure out it.
If you help me I will be happy.
Thanks.
答案1
得分: 2
只需在球的 y
坐标小于或等于 100 且大于或等于 300 时反转 ballSpeed
值:
y -= ballSpeed;
if (y <= 100 || y >= 300) {
ballSpeed = -ballSpeed;
}
注意球是向上移动的。当球到达 100 时,会反转 ballSpeed
值,球改变方向并向下移动。如果球到达初始位置(300),ballSpeed
会再次反转,球再次改变方向。
如果希望在球的 y
坐标达到 100 时,球重新从 300 处开始,只需将 y
设置为 300:
y -= ballSpeed;
if (y <= 100) {
y = 300;
}
英文:
Just invert ballSpeed
, if the y
coordinate of the ball is less or equal 100 respectively greater or equal 300:
y -= ballSpeed;
if (y <= 100 || y >= 300) {
ballSpeed = -ballSpeed;
}
Note the ball is moving upwards. When the ball reaches 100, ballSpeed
is inverted, the ball changes direction and moves downwards. If the ball reaches is original position (300), ballSpeed
is inverted again and the ball changes the direction again.
If you want that the ball restarts at 300, when it reaches a y
coordinate of 100, then it is sufficient to set y = 300
:
y -= ballSpeed;
if (y <= 100) {
y = 300;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论