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.

172 <strong>Learning</strong> <strong>Processing</strong><br />

// Move and display balls<br />

ball1.move();<br />

ball2.move();<br />

ball1.display();<br />

ball2.display();<br />

}<br />

Now that we have set up our system for having two circles moving around the screen, we need <strong>to</strong> develop<br />

an algorithm for determining if the circles intersect. In <strong>Processing</strong> , we know we can calculate the distance<br />

between two points using the dist( ) function (see Chapter 7). We also have access <strong>to</strong> the radius of each<br />

circle (the variable r inside each object). Th e diagram in Figure 10.3 shows how we can compare the<br />

distance between the circles and the sum of the radii <strong>to</strong> determine if the circles overlap.<br />

fi g. 10.3<br />

R 1<br />

OK, so assuming the following:<br />

• x 1, y 1: coordinates of circle one<br />

• x 2, y 2: coordinates of circle two<br />

• r 1: radius of circle one<br />

• r 2: radius of circle two<br />

We have the statement:<br />

DIST<br />

R 2<br />

DIST > (R1 + R2)<br />

NOT INTERSECTING<br />

R 1<br />

DIST<br />

R 2<br />

DIST < (R1 + R2)<br />

INTERSECTING<br />

If the distance between (x 1,y 1 ) and (x 2,y 2 ) is less than the sum of r 1 and r 2, circle one intersects<br />

circle two.<br />

Our job now is <strong>to</strong> write a function that returns true or false based on the above statement.<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 />

}

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

Saved successfully!

Ooh no, something went wrong!