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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

230 <strong>Learning</strong> <strong>Processing</strong><br />

Example 14-2: Multiple translations<br />

void setup() {<br />

size(200,200);<br />

smooth();<br />

}<br />

void draw() {<br />

background(255);<br />

stroke(0);<br />

fill(175);<br />

// Grab mouse coordinates, constrained <strong>to</strong> window<br />

int mx = constrain(mouseX,0,width);<br />

int my = constrain(mouseY,0,height);<br />

// Translate <strong>to</strong> the mouse location<br />

translate(mx,my);<br />

ellipse(0,0,8,8);<br />

// Translate 100 pixels <strong>to</strong> the right<br />

translate(100,0);<br />

ellipse(0,0,8,8);<br />

// Translate 100 pixels down<br />

translate(0,100);<br />

ellipse(0,0,8,8);<br />

// Translate 100 pixels left<br />

translate(–100,0);<br />

ellipse(0,0,8,8);<br />

}<br />

Now that we understand how translate( ) works, we can return <strong>to</strong> the original problem of specifying 3D<br />

coordinates. translate( ) , unlike rect( ), ellipse( ) , and other shape functions, can accept a third argument for<br />

a Z coordinate.<br />

// Translation along the z-axis<br />

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

rectMode(CENTER);<br />

rect(100,100,8,8);<br />

Th e above code translates 50 units along the Z -axis, and then draws a rectangle at (100,100). While the<br />

above is technically correct, when using translate( ) , it is a good habit <strong>to</strong> specify the ( x , y ) location as part<br />

of the translation, that is:<br />

// Translation along the z-axis II<br />

translate(100,100,50);<br />

rectMode(CENTER);<br />

rect(0,0,8,8); When using translate(), the rectangle’s location<br />

is (0,0) since translate() moved us <strong>to</strong> the location<br />

for the rectangle.<br />

fi g. 14.4<br />

Finally, we can use a variable for the Z location and animate the shape moving <strong>to</strong>ward us.

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

Saved successfully!

Ooh no, something went wrong!