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.

Figure 11-13. Weight on a Spring sketch<br />

Notice the actual springing code in the setSpring() function:<br />

// spring behavior<br />

y += cos(radians(angle))*amplitude;<br />

amplitude*=damping;<br />

angle+=frequency;<br />

This code is very similar to other trig expressions used throughout the book. Again, by<br />

damping a simple sine or cosine wave over time, you can create pretty realistic spring<br />

motion. Lastly, notice within the createSpring() function that I used the modulus operator<br />

(%) when drawing the spring. I needed a way of alternating the plotting of the spring<br />

coil right <strong>and</strong> left. By using the if...else block with the condition (i%2==0)—only an<br />

even number leaves a remainder of 0 when divided by 2—I was able to accomplish this<br />

easily.<br />

We can build upon this concept by simulating some values for mass <strong>and</strong> spring strength. In<br />

the next sketch, shown in Figure 11-14, I create a series of springs that have varying sizes<br />

(representing differences in mass) <strong>and</strong> spring strengths, illustrated by varying the stroke<br />

weight when drawing the springs. Based on these variations, the sketch simulates how<br />

these different configurations might move. For example, a heavy weight attached to a<br />

spring with a small rod diameter would stretch further than the same weight on a spring<br />

with a wider diameter. The damping effect of the spring is based on the stroke weight as<br />

well. Each time you run the sketch or click the mouse in the display window, r<strong>and</strong>om<br />

values are generated for mass <strong>and</strong> spring strengths.<br />

// Weights on Springs<br />

int weights = 5;<br />

float[]x = new float[weights];<br />

float[]y = new float[weights];<br />

float[]w = new float[weights];<br />

float[]h = new float[weights];<br />

float[]angle = new float[weights];<br />

MOTION<br />

513<br />

11

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

Saved successfully!

Ooh no, something went wrong!