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

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

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

PROCESSING: CREATIVE CODING AND COMPUTATIONAL ART<br />

556<br />

class Ball{<br />

float x, y, r, m;<br />

// default constructor<br />

Ball() {<br />

}<br />

Ball(float x, float y, float r) {<br />

this.x = x;<br />

this.y = y;<br />

this.r = r;<br />

m = r*.1;<br />

}<br />

}<br />

If it isn’t obvious, all I added was a mass property to the class <strong>and</strong> based its value on the<br />

radius. Of course, the mass could also be coded as a completely separate value from<br />

the radius, as, for example, a large cork ball would certainly weigh less than a much<br />

smaller steel ball bearing. That being said, tying the mass to the radius was easiest.<br />

The checkObjectCollision() function is where the majority of changes are, <strong>and</strong> of course<br />

it’s where the scary conservation of momentum expressions are coded:<br />

void checkObjectCollision(Ball[] b, Vect2D[] v){<br />

float d = dist(b[0].x, b[0].y, b[1].x, b[1].y);<br />

if (d < b[0].r + b[1].r){<br />

/* calculate final velocities based on<br />

Law of Conservation of Momentum */<br />

float finalVel0 = ((b[0].m - b[1].m) * v[0].vx + 2 *➥<br />

b[1].m * v[1].vx) / (b[0].m + b[1].m);<br />

float finalVel1 = ((b[1].m - b[0].m) * v[1].vx + 2 *➥<br />

b[0].m * v[0].vx) / (b[0].m + b[1].m);<br />

v[0].vx = finalVel0;<br />

v[1].vx = finalVel1;<br />

}<br />

}<br />

Hopefully, you didn’t find the long expressions too frightening; they’re long but pretty<br />

straightforward, <strong>and</strong> of course there’s no obligation to really underst<strong>and</strong> why they work<br />

(but then I’m not your Physics teacher). Following the new expressions, I simply assign the<br />

final velocities to the original velocity variables.

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

Saved successfully!

Ooh no, something went wrong!