06.01.2013 Views

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Example 5-6: Bouncing ball<br />

// Declare global variables<br />

int x = 0;<br />

int speed = 1;<br />

void setup() {<br />

size(200,200);<br />

smooth();<br />

}<br />

void draw() {<br />

background(255);<br />

}<br />

// Change x by speed<br />

x = x + speed;<br />

// If we’ve reached an edge, reverse speed<br />

if ((x > width) || (x < 0)) {<br />

speed = speed * –1;<br />

}<br />

// Display circle at x location<br />

stroke(0);<br />

fill(175);<br />

ellipse(x,100,32,32);<br />

Move the ball!<br />

Bounce the ball!<br />

Display the ball!<br />

Functions 105<br />

Once we have determined how we want <strong>to</strong> divide the code up in<strong>to</strong> functions, we can take the pieces out<br />

of draw( ) and insert them in<strong>to</strong> function defi nitions, calling those functions inside draw( ) . Functions<br />

typically are written below draw( ) .<br />

Example 7-3: Bouncing ball with functions<br />

// Declare all global variables (stays the same)<br />

int x = 0;<br />

int speed = 1;<br />

// Setup does not change<br />

void setup() {<br />

size(200,200);<br />

smooth();<br />

}<br />

void draw() {<br />

background(255);<br />

move();<br />

bounce();<br />

display();<br />

}<br />

Instead of writing out all the code about the<br />

ball is draw(), we simply call three functions.<br />

How do we know the names of these<br />

functions? We made them up!

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

Saved successfully!

Ooh no, something went wrong!