Search code examples
for-loopbooleanprocessing

Letting a loop run back and forth in Processing


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;
}

Thank you for any help


Solution

  • It will probably be easier is you don't try to change the way you increment the steps but rather how many rectangles you generate for each step. To make it more clear consider this code:

    MAX_RECTANGLES = 15;
    let frameCount = 0;
    
    while (frameCount < 100) {
      frameCount++;
    
      step = frameCount % (MAX_RECTANGLES * 2);
      nbRect = MAX_RECTANGLES - Math.abs(MAX_RECTANGLES - step);
    
      console.log(step, nbRect);
    }
    

    The frameCount variable and the while loop are only recreating the p5js loop, what is interesting here are the step and nbRect variables:

    • MAX_RECTANGLES is the number of rectangles you want to show when you show them all. In our example we want to show 15 rectangles.
    • step will will vary between 0 and MAX_RECTANGLES * 2 in our example this will vary between 0 and 30.
    • And we will vary nbRect between 0 and 15 with the following rules:
      • If 0 <= step <= 15 then 0 <= nbRect <= 15
      • If 16 <= step <= 30 then 15 >= nbRect >= 0

    Running the code might make it easier to understand. With this mechanism you transform an ever increasing value (frameCount) to a value varying between 0 and 15.

    You can have a look at this p5js codepen which does what you want with the method I just described.