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 />

98<br />

Figure 3-7. R<strong>and</strong>om rectangles<br />

This example begins to reveal the power of functions. By passing, or inputting, different<br />

values to the function, you can generate very different results. Functions create efficiencies<br />

by helping you avoid writing redundant code. They also free you from having to write<br />

all your code linearly, from top bottom, in your sketch. Once you define a function, you<br />

can call it when you need it, as well as multiple times, as I did in the last example. The next<br />

sketch uses <strong>Processing</strong>’s built-in draw() function to move a box across the screen.<br />

<strong>Processing</strong>’s draw() function is called automatically when you include it in your sketch.<br />

The draw() function increments the value of two speed variables I created (xspeed <strong>and</strong><br />

yspeed), which are assigned to two position variables I created (xpos <strong>and</strong> ypos). xpos <strong>and</strong><br />

ypos control the x <strong>and</strong> y positions of the box.<br />

// simple ball<br />

int xpos, ypos;<br />

int xspeed=3;<br />

int yspeed=5;<br />

void setup(){<br />

size(400, 400);<br />

}<br />

void draw(){<br />

background(0);<br />

rect(xpos, ypos, 10, 10);<br />

xpos+=xspeed;<br />

ypos+=yspeed;<br />

if (xpos>=width-10 || xpos=width-10 || ypos

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

Saved successfully!

Ooh no, something went wrong!