如何在processing中使3D球体在Y坐标上重复?

huangapple go评论109阅读模式
英文:

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 &lt;= 100 || y &gt;= 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 &lt;= 100) {
    y = 300;
} 

huangapple
  • 本文由 发表于 2020年5月31日 04:28:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/62108286.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定