redraw question

edited February 2017 in Questions about Code

Simple question: In the code below calling drawsomething() draws a rectangle every 500 ms. Using redraw instead does not work. Why? Am I missing something?

int i = 0;
float time = 0;

void setup() {
  size (300, 300);
  noLoop();

  while (time < 3000) {
    time = millis();
    if (time > i*500) {  
      drawsomething();
      //redraw();
      print(i);
      i++;
    }
  }
}

void drawsomething() {
  background(0);
  fill(255);
  rect(10, 10, 20, 20);
}

void draw() {
  background(0);
  fill(255);
  rect(10, 10, 20, 20);
}

Answers

  • Answer ✓

    This is from the Processing reference on 'redraw()':

    In structuring a program, it only makes sense to call redraw() within events such as mousePressed(). This is because redraw() does not run draw() immediately (it only sets a flag that indicates an update is needed).

  • Okay, got it. Thanks.

  • edited February 2017

    @blast664 --

    It is also important to understand that draw() is how time happens in Processing -- setup won't update the screen more than once, so embedding time loops for progressive rendering in setup() is pointless. Periodic screen drawing is what draw() is for -- that's why it is called draw.

    draw() already works using timer code, and Processing has a built-in call rate (frameRate()), time value since start (millis()), and a frame counter (frameCount) -- you don't need to define or update any of these things (your i and time are not needed)

    Given that, if your goal is "run draw every 500 milliseconds until 3000ms" then there are many ways to do it, but they are structured more like this:

    void setup() {
      size (300, 300);
      frameRate(2); // just set ~500 ms calls to draw
    }
    
    // draw runs at frameRate
    void draw() {
      if (millis()<6000) { // just use time since start
        background(0);
        fill(255);
        rect(10, 10, 20, 20);
        text(frameCount, width/2, height/2); // just use frame count
        println(frameCount, millis());
      }
    }
    

    Note that you can sometime get a half-second to a second of lag on startup before your first few frames render -- depending on library code and especially if calling text() for the first time.

  • Thanks for the answer. My example was just to illustrate my quenstion. What I missed was the fact, that redraw() just sets the flag for drawing.

    What I actually wanted to do, is to execute some code independently from the draw function with a higher frequency than the framerate. I now use the thread() function for this. So im my case the GUI and some other graphical elements are updated with 30 or 60 frames per second and the actual time-critical code runs 120 or 240 times per second.

Sign In or Register to comment.