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.

void setup(){<br />

size(400, 400);<br />

}<br />

void draw(){<br />

background(0);<br />

rotate(frameCount*PI/60);<br />

rect(50, 50, 150, 150);<br />

}<br />

If you run the sketch, you may be surprised to see the rectangle rotating off the screen,<br />

around the origin, instead of around its own center point. This is a common error new<br />

coders make. Intuitively, it seems that rotate() should spin the shape around its center<br />

point. However, rotate() doesn’t actually spin the shape; it spins the entire contents of<br />

the display window. If you’re used to graphics applications like Illustrator, FreeH<strong>and</strong>, or<br />

Flash, which internally h<strong>and</strong>le translations when you draw highly encapsulated shape<br />

objects, it can seem frustrating to have to think about the translation process in<br />

<strong>Processing</strong>. A basic rule of thumb is to draw your objects initially around the origin (0, 0,<br />

0) <strong>and</strong> then translate them. Here’s a new version of the last sketch, correctly implemented<br />

for centered rotation:<br />

void setup(){<br />

size(400, 400);<br />

}<br />

void draw(){<br />

background(0);<br />

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

rotate(frameCount*PI/60);<br />

rect(-75, -75, 150, 150);<br />

}<br />

The order of transformations also has an effect on how <strong>and</strong> where in the display window<br />

things are drawn.<br />

The next sketch (see Figure 13-3) uses <strong>Processing</strong>’s sphere() function. I call translate()<br />

after rotateY(), which doesn’t get the sphere rotating around the center of the window.<br />

However, if I switch the order of the rotateY(frameCount*PI/60); <strong>and</strong> translate(width/2,<br />

height/2); comm<strong>and</strong>s, the rotation happens as expected, around the center of the<br />

window.<br />

void setup(){<br />

size(400, 400, P3D);<br />

}<br />

void draw(){<br />

background(0);<br />

// the next 2 lines should be switched in order<br />

rotate(frameCount*PI/60);<br />

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

sphere(100);<br />

}<br />

3D<br />

619<br />

13

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

Saved successfully!

Ooh no, something went wrong!