Articles

Assignments

Resources

Structure, Logic & Animation

September 16, 2011
by Haig.
Average Reading Time: about a minute.

Until now our scripts have been nothing more than a short list of instructions to perform, after which they stop. But with anything beyond the most basic level of programming, we will need to go further and group instructions and provide some decisions. It’s time to step it up a notch.

The Frame Loop

The frame can mean a variety of things within the computer sciences, but our meaning is the movie industry sense – a single still image which, if we flash enough of them fast enough, it would give the illusion of movement or animation.

With Processing, a frame loop redraws the screen continuously. If you instruct Processing to do so, you can use this feature to add the dimension of time to your two-dimensional visuals and can create works that grow and move.

To enable this way of drawing to the screen, we need to begin putting our code into function blocks. Processing sets aside two function blocks for frame-based scripting: setup() and draw().

setup()The code inside the setup() function block is called once when the program launches, so it should contain all your initialization code – setting the canvas size, setting the background colour, initializing variables, and so on.

draw()The code you write inside draw() is then called repeatedly, triggered on every frame. You can set the speed with which draw() is called by using the frameRate function. The program will work to maintain the rate which you set and will only deviate from this frame rate if the amount of computations exceed the capacity of the processor which is running the program.

void setup(){
code...// This code block will run only once,
… // at the start of the sketch.
…
}
void draw(){
code...// This code block with run repeatedly,
… // throughout the duration of the sketch.
…
}

Want to see this structure in action? See the simple Growing Circle exercise.