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.

selection can be active at a time. The function, by receiving the index of the current tool,<br />

resets the other unselected tools, including setting their up states.<br />

If you’ve entered all the code in the order I presented it, your drawing application should<br />

now be able to be run. Please remember that if you don’t have the typeface Arial installed<br />

(you probably do), you’ll need to specify a different (installed) typeface on your computer,<br />

in the following two lines:<br />

titleFont = createFont("Arial", 11);<br />

clearFont = createFont("Arial", 10);<br />

Remember to also add the cursor PNGs to the sketch’s data directory.<br />

Whew! I realize that was a lot of code, but hopefully you’re starting to see the redundancy,<br />

especially in the GUI implementation. By restructuring a program like this using an objectoriented<br />

approach, you could eliminate some of the redundancy (but not necessarily use<br />

less code). If I were going to scale this program to a much larger application, the added<br />

organizational aspects of OOP would make it worthwhile to do so.<br />

Keystroke events<br />

In addition to mouse events, interactivity often includes keystroke events. As usual,<br />

<strong>Processing</strong> simplifies the process, making it really easy to add keystroke control to your<br />

sketches. <strong>Processing</strong> includes built-in functions to detect key presses <strong>and</strong> releases <strong>and</strong> to<br />

also determine what specific key was pressed. For example, this sketch changes the rectangle’s<br />

color to red on the key press <strong>and</strong> blue on the key release:<br />

color rectBackground = color(0, 0, 255);<br />

void setup(){<br />

size(400, 400);<br />

background(255);<br />

rectMode(CENTER);<br />

}<br />

void draw(){<br />

fill(rectBackground);<br />

rect(width/2, height/2, 200, 200);<br />

}<br />

void keyPressed(){<br />

rectBackground = color(255, 0, 0);<br />

}<br />

void keyReleased(){<br />

rectBackground = color(0, 0, 255);<br />

}<br />

Obviously, you’ll usually want to know what key was pressed when detecting a key event.<br />

The next sketch adds arrow key detection to the key press event, giving each directional<br />

arrow control over a different color fill:<br />

INTERACTIVITY<br />

603<br />

12

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

Saved successfully!

Ooh no, something went wrong!