04.04.2013 Views

Processing: Creative Coding and Computational Art

Processing: Creative Coding and Computational Art

Processing: Creative Coding and Computational Art

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

PROCESSING: CREATIVE CODING AND COMPUTATIONAL ART<br />

484<br />

In the previous Java example, notice that I explicitly instantiate a Thread object:<br />

Thread t = new Thread(this);<br />

A few lines later, in the run() method, notice the following block:<br />

try {<br />

Thread.sleep(30);<br />

}<br />

catch (InterruptedException e){<br />

}<br />

The run() method continuously executes, which is where the drawing happens, <strong>and</strong> the<br />

Thread.sleep(30) call adds a delay between each execution (or frame); the larger<br />

the delay value, the slower the animation. Finally, I also needed to call the comm<strong>and</strong><br />

repaint(), which forces the screen to be updated each frame—allowing you to see the<br />

animation. Whew! That’s a lot to deal with. Fortunately, you don’t need to worry about<br />

most of this stuff in <strong>Processing</strong>.<br />

In the <strong>Processing</strong> example, notice the draw() function. This <strong>Processing</strong> function encapsulates<br />

most of the annoying stuff involved in creating animations with threads in the Java<br />

example. Simply including the draw() function in your sketch causes a thread to begin<br />

running (under the hood).<br />

In the last two examples, the actual animation involved a rectangle moving across the<br />

screen. If it wasn’t obvious, the variable x was incremented by xspd each frame, <strong>and</strong> then<br />

the rectangle was drawn with the updated x value. In a sense, I simply redrew the rectangle<br />

over <strong>and</strong> over again, at a different x position. The reason you don’t see all the previous<br />

drawn rectangles is because of the call background(255); at the top of the draw() function.<br />

This call fills the screen with white between each frame, painting over the previous<br />

rectangle. This repainting of the background between draw frames is what gives the<br />

illusion that a single rectangle is moving across the screen. Try commenting out<br />

background(255); in the last sketch <strong>and</strong> rerunning it (see Figure 11-1).<br />

Figure 11-1. Sketch with background() commented out

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!