06.01.2013 Views

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

14.9<br />

Example 14-17: Nested push and pop<br />

// Global angle for rotation<br />

float theta = 0;<br />

void setup() {<br />

size(200, 200);<br />

smooth();<br />

}<br />

void draw() {<br />

background(100);<br />

stroke(255);<br />

// Translate <strong>to</strong> center of window<br />

translate(width/2,height/2);<br />

// Loop from 0 <strong>to</strong> 360 degrees (2*PI radians)<br />

for(float i = 0; i < TWO_PI; i + = 0.2) {<br />

// Push, rotate and draw a line!<br />

pushMatrix();<br />

rotate(theta + i);<br />

line(0,0,100,0);<br />

// Loop from 0 <strong>to</strong> 360 degrees (2*PI radians)<br />

for(float j = 0; j < TWO_PI; j + = 0.5) {<br />

// Push, translate, rotate and draw a line!<br />

pushMatrix();<br />

translate(100,0);<br />

rotate(–theta–j);<br />

line(0,0,50,0);<br />

// We're done with the inside loop, pop!<br />

popMatrix();<br />

}<br />

// We're done with the outside loop, pop!<br />

popMatrix();<br />

}<br />

endShape();<br />

// Increment theta<br />

theta + = 0.01;<br />

}<br />

Translation and Rotation (in 3D!) 249<br />

Exercise 14-9: Take either your pyramid or your cube shape and make it in<strong>to</strong> a class. Have<br />

each object make its own call <strong>to</strong> pushMatrix( ) and popMatrix( ) . Can you make an array<br />

of objects all rotating independently in 3D?<br />

A <strong>Processing</strong> Solar System<br />

Using all the translation, rotation, pushing, and popping techniques in this chapter, we are ready <strong>to</strong> build<br />

a <strong>Processing</strong> solar system. Th is example will be an updated version of Example 14-16 in the previous<br />

section (without any moons), with two major changes:<br />

• Every planet will be an object, a member of a Planet class.<br />

• An array of planets will orbit the sun.<br />

fi g. 14.30<br />

The transformation state is saved<br />

at the beginning of each cycle<br />

through the for loop and res<strong>to</strong>red<br />

at the end. Try commenting out<br />

these lines <strong>to</strong> see the difference!

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

Saved successfully!

Ooh no, something went wrong!