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.

246 <strong>Learning</strong> <strong>Processing</strong><br />

Although technically not required, it is a good habit <strong>to</strong> place pushMatrix( ) and popMatrix( ) around<br />

the second rectangle as well (in case we were <strong>to</strong> add more <strong>to</strong> this code). A nice rule of thumb when<br />

starting is <strong>to</strong> use pushMatrix( ) and popMatrix( ) before and after translation and rotation for all shapes<br />

so that they can be treated as individual entities. In fact, this example should really be object oriented,<br />

with every object making its own calls <strong>to</strong> pushMatrix( ), translate( ), rotate( ) , and popMatrix( ) .<br />

See Example 14-5 .<br />

Example 14-15: Rotating many things using objects<br />

// An array of Rotater objects<br />

Rotater[] rotaters;<br />

void setup() {<br />

size(200,200);<br />

rotaters = new Rotater[20];<br />

// Rotaters are made randomly<br />

for (int i = 0; i < rotaters.length; i + + ) {<br />

rotaters[i] = new Rotater(random(width),random(height),random(–0.1,0.1),random(48));<br />

}<br />

}<br />

void draw() {<br />

background(255);<br />

// All Rotaters spin and are displayed<br />

for (int i = 0; i < rotaters.length; i + + ) {<br />

rotaters[i].spin();<br />

rotaters[i].display();<br />

}<br />

}<br />

// A Rotater class<br />

class Rotater {<br />

float x,y; // x,y location<br />

float theta; // angle of rotation<br />

float speed; // speed of rotation<br />

float w; // size of rectangle<br />

Rotater(float tempX, float tempY, float tempSpeed, float tempW) {<br />

x = tempX;<br />

y = tempY;<br />

theta = 0; // Angle is always initialized <strong>to</strong> 0<br />

speed = tempSpeed;<br />

w = tempW;<br />

}<br />

// Increment angle<br />

void spin() {<br />

theta + = speed;<br />

}<br />

// Display rectangle<br />

void display() {<br />

rectMode(CENTER);<br />

stroke(0);<br />

fi g. 14.27

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

Saved successfully!

Ooh no, something went wrong!