how to draw inside a for loop

Hello, is there a way to call the draw() function inside a for loop?

For example, let's say I want to animate 9 frames. In frame 1 I need a text that writes "a1", in the next frame the text has to be "a2", next "a3", next "b1", next "b2", next "b3", then "c1", "c2", "c3".

I came up with a code like this:

String message = ""; 
void setup() {
  size(500,500);
  noLoop();
}

void draw() {
  text(message, 200, 200);
}

for(char l = 'a'; l <= 'c'; l++) {
  for(int n = 1; n <= 3; n++) {
    message = String.valueOf(l) + String.valueOf(n);
    redraw();
  }}

This does not work, and I kind of understand why, but is there a way to make it work? I mean, to draw at each frame an iteration of the for loop, or to call the draw function inside the for loop?

Tagged:

Answers

  • You could approach this in a number of ways -- but it seems that for animation you may actually still want to use the functions of draw() (framerate, ability to pause/unpause looping, etc.) -- you can't do this through redraw(). Given that, here are two alternatives to making a redraw timer function or creating a thread:

    • Option 1: turn your nested for loops inside out. Make the counter variables global, and check and iterate your nested counters in draw():

      if (number == numbermax && letter < lettermax) {
        number=numbermin;
        letter++;
      } else if (number < numbermax) {
        number++;
      }
      
    • Option 2: pre-compute your value sequence with nested loops (eg. in setup) and store them in an array.

      StringList slides = new StringList();
      for(char l = 'a'; l <= 'c'; l++) {
        for(int n = 1; n <= 3; n++) {
          slides.append("String.valueOf(l) + String.valueOf(n)");
        }
      }
      

      Then, each draw(), increment through your slides array with a single global counter.

  • Thank you very much for your answer and your time. Indeed, I have found a workaround for my specific application. I was just wondering if there was a straight way of using a for loop in the way it is in my example, but I understand there is not. It would be cool to find a way to implement it in the future.

  • @matteolengna --

    There are many solutions, but what it boils down to is that you only want one step in a 2D sequence each time. That probably means unwinding the results -- global variables, or a list or array. Solutions look like this:

    draw(){ // this is how Processing makes time happen
       getNextFrame() // advance to next part of nested loops
    }
    getNextFrame(){
      //draw something
    }
    

    Your first stab at the problem is difficult because it would work like this:

    timeHappensSomehow(){
      for(){
        for(){
          draw(){ // makes ti... no, wait a minute....
        }
      }
    }
    draw(){ // now I'm just confused
      // draw something
    }
    
Sign In or Register to comment.