Letting a loop run forth and back

Currently I am trying to get a loop “running forth and back” in a Processing sketch. I can do it with mouseY for example – but I want to have it automatically: the rect(); should appear horizontally line by line… like 1, 1+next, 1+next+next and after 15 lines reverse! 15, 14, 13, 12,11,10,9… With
frameCount; I can let them run down as I want… but not yet back. So I read about boolean statements… and tried to get it in syntax… syntax seems ok… but I can not really get the right logic to make it work. Does someone have an Idea how to really write it in the correct way? This is my Code so far:

int a;
int i;
int step = 60;
void setup() {
  size(1080, 1080);
}
void draw() {
  background(0);
for (a = 0; a < 15; a++) {
for (i = 0; i < 5; i++) {
  fill(255, 255, 255);
  rect(216*i,60*a,216,60);
}
 
  }
}

This creates the pattern – all at once – I know for (a = 0; a < mouseY; a++) or for (a = 0; a < frameCount; a++) would make it work but I thought to make it automatically this needs to appear somewhere – but how?

a+=step;
if ( a > 15 || a < 0 ){
step = -step;
}

Hello and welcome to the forum!

Great to have you here!

This </> doesn’t have to be typed but you select the text with the mouse and then click the symbol </> in the command bar.

Do you want to create an animation or a pattern?

A pattern is drawn all the same in every frame. For this, you can use the for loops as you have shown above. I will start with defining every for loop, the ones that draw the rectangle in the downward direction and the for loop to draw the rectangles in the upward direction. Then you can see if there is a pattern to simply the code. My recommendation is: keep it simple at first and keep your code readable.

If you want to do an animation, then I will object you would not need the for loops. Instead, I would use the draw() function, a variable keeping track of the step and a second variable keeping track of position. When you reach a limit (boundary), you reverse the sign of the step:
step = step * (-1); As you can see, step does not have to be 1 but any non-zero value. This is illustrated in the bounce example.

One more thing: I suggest you do this for(int a=....){ ...} Keep your counter definition within the scope of your loops as this is a better practice and it will avoid weird bugs in your code in the future.

Kf

1 Like