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.

174 <strong>Learning</strong> <strong>Processing</strong><br />

boolean intersecting = ball1.intersect(ball2);<br />

if (intersecting) {<br />

println( " The circles are intersecting! " );<br />

}<br />

}<br />

Following this model and the algorithm for testing intersection, here is a function for inside the ball class<br />

itself. Notice how the function makes use of both its own location ( x and y ) as well as the other ball’s<br />

location ( b.x and b.y ).<br />

// A function that returns true or false based on whether two Ball objects intersect<br />

// If distance is less than the sum of radii the circles <strong>to</strong>uch<br />

boolean intersect(Ball b) {<br />

float distance = dist(x,y,b.x,b.y); // Calculate distance<br />

if (distance < r + b.r) { // Compare distance <strong>to</strong> sum of radii<br />

return true;<br />

} else {<br />

return false;<br />

}<br />

}<br />

Putting it all <strong>to</strong>gether, we have the code in Example 10-3 .<br />

Example 10-3: Bouncing ball with intersection<br />

// Two ball variables<br />

Ball ball1;<br />

Ball ball2;<br />

void setup() {<br />

size(400,400);<br />

smooth();<br />

// Initialize balls<br />

ball1 = new Ball(64);<br />

ball2 = new Ball(32);<br />

}<br />

void draw() {<br />

background(255);<br />

// Move and display balls<br />

ball1.move();<br />

ball2.move();<br />

if (ball1.intersect(ball2)) {<br />

ball1.highlight();<br />

ball2.highlight();<br />

}<br />

ball1.display();<br />

ball2.display();<br />

}<br />

class Ball {<br />

float r; // radius<br />

float x,y;<br />

float xspeed,yspeed;<br />

color c = color(100,50);<br />

fi g. 10.4<br />

Assumes a function intersect() inside<br />

the Ball class that returns true or false.<br />

New! An object can have a function that takes<br />

another object as an argument. This is one<br />

way <strong>to</strong> have objects communicate. In this case<br />

they are checking <strong>to</strong> see if they intersect.

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

Saved successfully!

Ooh no, something went wrong!