Hello, 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 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 start from the first position and then again it should go to 100 again. I tried many if contions but couldn’t figure out it.
If you help me I will be happy.
Thanks.
1 Like
Have you tried storing the value of ball y starting position in its own variable?
- if ball y current position is less than or equal to 100
- then set ball y current position equal to ball y starting position
2 Likes
Thank you @slow_izzm I found the solution. Your idea is true.
Let me write down the code. It can helpfull for beginners.
y -= ballSpeed;
if (y <= 100) {
y = 300;
}
1 Like
Hello
and welcome to the forum!
Great to have you here!
note that a sphere looks better with lights()
here is a red one going back and forth (into the screen) - Z-axis
Warmest regards,
Chrisir
PShape ball;
float ballSpeed = -random(2.5, 3);
float ballSize = random(25, 35);
float x, y, z;
void setup() {
size(1400, 900, P3D);
x = width/2-150;
y = 860-ballSize;
z = 150;
noStroke(); // That's for "not see details / lines on sphere"
ball = createShape(SPHERE, ballSize);
ball.setFill(color(0, 255, 0));
}
void draw() {
background(0);
lights();
floor();
translate(x, y, z); // rotate the ball
println(z); // checking the y coordinates
shape(ball);
z += ballSpeed; // the ball can go to top
if (z <= -440) {
ballSpeed = abs(ballSpeed) ; // always pos
}
if (z > 0) {
ballSpeed = - abs(ballSpeed); // always neg
}
}//draw()
// ------------------------------------------------------------------------------------
// tab Floor
// Floor: CheckeredFloor
void floor () {
noStroke();
for (int i = 0; i < 30; i = i+1) {
for (int j = 0; j < 30; j = j+1) {
// % is modulo, meaning rest of division
if (i%2 == 0) {
if (j%2 == 0) {
fill (255, 0, 0);
} else
{
fill ( 103 );
}
} else {
if (j%2 == 0) {
fill ( 103 );
} else
{
fill (255, 0, 0);
}
} // if
pushMatrix();
translate ( 80*i-610, 860, 80*j-940 );
box ( 80, 7, 80); // one cell / tile
popMatrix();
} // for
} // for
}//floor
// ---------------------------------------------------------------------------------
2 Likes