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.

}<br />

}<br />

}<br />

}<br />

}<br />

// bottom display window edge<br />

if (nodeYPos[i]>height-nodeRadius){<br />

nodeYPos[i] = height-nodeRadius;<br />

xSpeed[i]+=jitter[i];<br />

xSpeed[i]*=friction;<br />

jitter[i]*=friction;<br />

ySpeed[i]*=-1;<br />

ySpeed[i]*=elasticity[i];<br />

The final function in the sketch, moveShape(), controls the movement of the shape. I<br />

nested all the motion code in the conditional block (isShapeClosed), which evaluates to<br />

true only if the shape is closed. The actual motion code should look familiar, as similar<br />

code was covered in Chapter 11. The for loop ensures that speed values are added to<br />

each of the shape’s nodes (the lines connecting the nodes rely on the nodes’ coordinates<br />

for their placement), <strong>and</strong> the collision code makes each node bounce off the sides <strong>and</strong><br />

bottom of the display window. The animation uses gravity <strong>and</strong> jitter, which simulate the<br />

shape falling with acceleration <strong>and</strong> deflecting off an irregular ground surface. The array<br />

variables elasticity[] <strong>and</strong> friction[] eventually bring the individual nodes to a stop at<br />

the bottom of the display window.<br />

Adding interface elements<br />

Next, I’ll look at creating more elaborate interface elements, such as interactive buttons.<br />

<strong>Processing</strong> doesn’t come with any native prebuilt buttons, but you can easily build them,<br />

as I sort of did in the last example when I tested if the mouse was pressed on the initially<br />

plotted node. The only difference between detecting a mouse event on a button <strong>and</strong><br />

detecting a mouse event on the entire display window is in the evaluation of the size of<br />

the bounded hit area (the area that detects the event). Of course, when building a user<br />

interface, you generally want to give the user more control than they get by simply clicking<br />

the screen.<br />

When creating a button, you can use <strong>Processing</strong>’s drawing/text functions or import a<br />

graphic—I’ll discuss both approaches in this chapter. This first sketch creates a single button<br />

that starts a simple animation of a rectangle moving across the screen:<br />

// Start Button<br />

// button<br />

float btnX, btnY, btnW, btnH;<br />

// moving rectangle<br />

float x = 25;<br />

INTERACTIVITY<br />

579<br />

12

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

Saved successfully!

Ooh no, something went wrong!