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.

Now that the function is complete, we can test it with data from ball1 and ball2.<br />

Algorithms 173<br />

boolean intersecting = intersect(ball1.x,ball1.y,ball2.x,ball2.y,ball1.r,ball2.r);<br />

if (intersecting) {<br />

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

}<br />

Th e above code is somewhat awkward and it will be useful <strong>to</strong> take the function one step further,<br />

incorporating it in<strong>to</strong> the ball class itself. Let’s fi rst look at the entire main program as it stands.<br />

// Two ball variables<br />

Ball ball1;<br />

Ball ball2;<br />

void setup() {<br />

size(400,400);<br />

framerate(30);<br />

smooth();<br />

// Initialize balls<br />

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

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

}<br />

void draw() {<br />

background(0);<br />

// Move and display balls<br />

ball1.move();<br />

ball2.move();<br />

ball1.display();<br />

ball2.display();<br />

boolean intersecting = intersect(ball1.x,ball1.y,ball2.x,ball2.y,ball1.r,ball2.r);<br />

if (intersecting) {<br />

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

}<br />

}<br />

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

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

boolean intersect(float x1, float y1, float x2, float y2, float r1, float r2) {<br />

float distance = dist(x1,y2,x2,y2); // Calculate distance<br />

if (distance < r1 + r2) { // Compare distance <strong>to</strong> r1 + r2<br />

return true;<br />

} else {<br />

return false;<br />

}<br />

}<br />

Since we have programmed the balls in an object-oriented fashion, it is not terribly logical <strong>to</strong> suddenly<br />

have an intersect( ) function that lives outside of the ball class. A ball object should know how <strong>to</strong> test if it<br />

is intersecting another ball object. Our code can be improved by incorporating the intersect logic in<strong>to</strong> the<br />

class itself, saying “ ball1.intersect (ball2); ” or, does Ball 1 intersect Ball 2?<br />

void draw() {<br />

background(0);<br />

// Move and display balls<br />

ball1.move();<br />

ball2.move();<br />

ball1.display();<br />

ball2.display();

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

Saved successfully!

Ooh no, something went wrong!