Search code examples
javaloopsprocessingrestartredraw

How to redraw - restart a loop in Processing


I would like to reset the "for" loop that is running in the sketch without use keyPressed() or mousePressed() it should happen automatically.

When the stroke will is going to cover most of the canvas area or when it goes over the width/height I would like to restart the sketch.

In a previous sketch I set a counter, it was working because there was no "for" loop but in this one the counter does not work because of it.

int interval = 5 * 1000;
int time;

float cer;
float big = 14;

void setup() {
  size(595, 842);
  background(255);
}

void draw() {
  strokeWeight(cer);
  stroke(0);
  noFill();
  ellipse(width/2, height/2-100, 200, 200);
  ellipse(width/2, height/2+100, 200, 200);

  cer = cer + big;

  if (cer < width) {
    big = +1;
  }

  if (millis() - time >= interval) {
    // clear background
    background(255);
    // reset time for next interval
    time = millis();
    // debug
    println("=========================>  tick");
  }
}


Solution

  • Just rest the values of cer and big to its initial state and you've to clear the background when the process has to be restart:

    float cer = 0;
    float big = 14;
    
    void draw() {
    
        // [...]
    
        cer = cer + big;
    
        if (cer < width) {
            big = +1;
        } else {
            // clear background
            background(255);
    
            // reset to initial state 
            cer = 0;
            big = 14;
        }
    
        // [...]
    } 
    

    Note, big = +1; is the same as big = 1;. I just assigns 1 to big.
    Probably you've been searching for big += 1;, which would increment big by 1:

    float cer = 0;
    float big = 0;
    
    void draw() {
    
        // [...]
    
        cer = cer + big;
    
        println(cer, big);
        if (cer < width) {
            big += 1;
        } else {
            background(255);
            cer = 0;
            big = 0;
        }
    
        // [...]
    
    }