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.

A lot more can be done with this code, including creating an autonomous prey object <strong>and</strong><br />

using it instead of the mouse. A simple tank game could be created, with a computercontrolled<br />

tank <strong>and</strong> a user-controlled one. The atan2() function will ensure that the tanks<br />

(or the tanks’ gun turrets) stay oriented in the correct direction as they move.<br />

Springing<br />

Another fun effect to experiment with is springing. In the last few examples, the predator<br />

followed the prey, but never overshot it. There are times, though, when you might want an<br />

object to slingshot past another object <strong>and</strong> eventually come to rest. Think about a<br />

small rubber ball on an elastic string, <strong>and</strong> how it bounces around before coming to rest.<br />

Working with accurate spring equations is somewhat involved, <strong>and</strong> more than you need<br />

for most aesthetics-based creations. We can very easily simulate spring behavior just by<br />

tweaking the code used in the predator/prey scenario. In fact, the tweak we need is very<br />

similar to the tweak used to add acceleration (with gravity) to the speed example earlier in<br />

the chapter.<br />

Here’s the Ravenous Triangle I sketch converted to use a springy (yet still ravenous)<br />

triangle:<br />

// Ravenous Triangle II<br />

float predCntrX, predCntrY;<br />

float predX[] = new float[3];<br />

float predY[] = new float[3];<br />

float predLen = 8.0;<br />

float predAng, predRot;<br />

// springing variables<br />

float accelX, accelY;<br />

float springing = .01, damping = .95;<br />

void setup(){<br />

size(400, 400);<br />

predCntrX = width/2;<br />

predCntrY = height/2;<br />

smooth();<br />

}<br />

void draw(){<br />

// repaint background<br />

fill(255, 40);<br />

rect(0, 0, width, height);<br />

/* find distance for x <strong>and</strong> y<br />

between prey <strong>and</strong> predator */<br />

float deltaX = (pmouseX-predCntrX);<br />

float deltaY = (pmouseY-predCntrY);<br />

MOTION<br />

505<br />

11

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

Saved successfully!

Ooh no, something went wrong!