Sequence of actions from array

Ways to approach this depend on on if you want things moving, or shown / hidden, or colored, et cetera.

A generic way to hand this is a set of event commands as data. So here is an event processor that draws colored squares:

void eventSquare(color c) {
  fill(c);
  rect(200, 200, 100, 100);
}

Now if we have set of times and colors, like this:

color / frame to display
0 / 60
127 / 120
255 / 180

Our goal is to save them as data, then check our data and if the frame matches, call the event action.

There are many ways to save them as data. We could use a simple array:

int[][] events = new int[3][];
events[0] = new int[] { color(0), 60 };
events[1] = new int[] { color(128), 120 };
events[2] = new int[] { color(255), 180 };

…or an ArrayList, or custom classes. But no matter what, at draw time we check, and if the frameCount matches, we pass the color to our function:

for(int i=0; i<events.length; i++) {
  if(events[i][1] == frameCount) {
    eventSquare(events[i][0]);
  }
}

Here it is playing the timed animation when you put it all together:

int[][] events = new int[3][];

void setup() {
  size(400, 400);
  events[0] = new int[] { color(0), 60 };
  events[1] = new int[] { color(128), 120 };
  events[2] = new int[] { color(255), 180 };
}

void draw() {
  for (int i=0; i<events.length; i++) {
    if (events[i][1] == frameCount) {
      eventSquare(events[i][0]);
    }
  }
}

void eventSquare(color c) {
  fill(c);
  rect(200, 200, 100, 100);
}

So, in general, don’t pass the time to your drawing function and then decide on the time using if / else or switch. Instead, loop over your time data and check for matches. After you decide what to draw, then call the drawing function with the appropriate arguments.

2 Likes