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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

void setup(){<br />

size(400, 400);<br />

// initialize x, y<br />

x = width/2.0;<br />

y = height/2.0;<br />

rectMode(CENTER);<br />

}<br />

void draw(){<br />

background(255);<br />

rect(x, y, w, h);<br />

if (mousePressed){<br />

x = mouseX;<br />

y = mouseY;<br />

}<br />

}<br />

This may seem confusing if you’re a new coder—why have two ways of doing the same<br />

thing? Well, if you run this last example, you’ll notice that the two sketches actually don’t<br />

run quite the same way. This last example updates the rectangle’s x <strong>and</strong> y positions continuously<br />

while the mouse is pressed, allowing the rectangle to be dragged in the display<br />

window. The earlier example only updated the rectangle when the mouse was pressed. As<br />

you look at some more complex examples, it will become clearer how these two<br />

approaches differ.<br />

Notice also when I checked the condition (true or false) of the mousePressed Boolean<br />

variable, I just included it between the parentheses: (mousePressed). I didn’t explicitly<br />

check if it was true using (mousePressed == true). This shortcut is perfectly legal, since<br />

the Boolean value will evaluate to either true or false, which is what the if statement<br />

needs to know in determining whether it should execute the code between its curly<br />

braces.<br />

In addition to mouse press events, you can detect mouse release events. Here’s an<br />

example:<br />

// mouseReleased<br />

// example 1<br />

// declare x, y<br />

float x, y;<br />

// declare <strong>and</strong> initialize w, h<br />

float w = 20.0, h = 20.0;<br />

// rectangle fill color variable<br />

color rectColor = color(255, 255, 255);<br />

void setup(){<br />

size(400, 400);<br />

// initialize x, y<br />

x = width/2.0;<br />

INTERACTIVITY<br />

567<br />

12

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

Saved successfully!

Ooh no, something went wrong!