Why does display come last in a function

edited November 14 in Programming Questions

I am working through Shiffman's Learning Processing book. I notice that when using functions or classes, the function that deals with "displaying" an object always appear last in draw(). Anything that deals with movement appears first. Does anyone know a reason for that? Is it a rule or just a standard? I hope I've given enough information.


  • edited November 14

    In any animation there are two parts
    1) Updating state of the objects - calculating new positions, collision detection etc.
    2) Displaying the current state of the objects.

    They are usually done in that order because then each frame represents the current state of the animation.

  • edited November 15
    1. Position gets calculated

    2. Object gets displayed

    Now, we have the object’s variables set to some numerals and the object displayed exactly according to these numerals. Think: what will happen if it occurred the other way around:

    1. Object gets displayed (at the old values of its variables)

    2. Position gets calculated

    Now, we have an object displayed according to the old values of its variables and we have the object’s varibles set to numerals that do not correspond perfectly to the object’s actual location.

    Obviously this can cause issues.

  • Edge case: There are binary conditions at low frameRates where you might want to update variables in the draw loop after drawing -- especially for interactive sketches, where the events are processed in the gap between frame updates.

    For example, consider this sketch: it displays either red or green, once a second.

    boolean on;
    void setup() {
    void draw() {
      if (on) {
        background(0, 255, 0);
      } else {
        background(255, 0, 0);

    We decide to turn it into a simple game by adding a keyPressed check. Press a key while the sketch is green, get a hit.

    void keyPressed(){
      if(on) {
        text("YES", width/2, height/2);
      } else {
        text("NO", width/2, height/2);

    However, weirdly, everything is backwards! Pressing a key while the sketch is red (off) prints "YES", pressing a key while green (on) prints "NO." That's not what the code appears to say. What is going on?

    Moving the update of variables (on=!on;) to the bottom of draw, below the actual drawing, would be one way to solve this problem.

Sign In or Register to comment.