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 />

558<br />

ellipse(balls[i].x, balls[i].y, balls[i].r*2, balls[i].r*2);<br />

checkBoundaryCollision(balls[i], vels[i]);<br />

}<br />

checkObjectCollision(balls, vels);<br />

}<br />

The checkObjectCollision() function needs a few more changes than that; here it is<br />

(brace yourself):<br />

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

// get distances between the balls' components<br />

Vect2D bVect = new Vect2D();<br />

bVect.vx = b[1].x - b[0].x;<br />

bVect.vy = b[1].y - b[0].y;<br />

// calculate magnitude of the vector separating the balls<br />

float bVectMag = sqrt(bVect.vx * bVect.vx + bVect.vy * bVect.vy);<br />

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

// get angle of bVect<br />

float theta = atan2(bVect.vy, bVect.vx);<br />

// precalculate trig values<br />

float sine = sin(theta);<br />

float cosine = cos(theta);<br />

/* bTemp will hold rotated ball positions. You<br />

just need to worry about bTemp[1] position*/<br />

Ball[] bTemp = { new Ball(), new Ball() };<br />

/* b[1]'s position is relative to b[0]'s<br />

so you can use the vector between them (bVect) as the<br />

reference point in the rotation expressions.<br />

bTemp[0].x <strong>and</strong> bTemp[0].y will initialize<br />

automatically to 0.0, which is what you want<br />

since b[1] will rotate around b[0] */<br />

bTemp[1].x = cosine * bVect.vx + sine * bVect.vy;<br />

bTemp[1].y = cosine * bVect.vy - sine * bVect.vx;<br />

// rotate Temporary velocities<br />

Vect2D[] vTemp = { new Vect2D(), new Vect2D() };<br />

vTemp[0].vx = cosine * v[0].vx + sine * v[0].vy;<br />

vTemp[0].vy = cosine * v[0].vy - sine * v[0].vx;<br />

vTemp[1].vx = cosine * v[1].vx + sine * v[1].vy;<br />

vTemp[1].vy = cosine * v[1].vy - sine * v[1].vx;<br />

/* Now that velocities are rotated, you can use 1D<br />

conservation of momentum equations to calculate<br />

the final velocity along the x-axis. */<br />

Vect2D[] vFinal = { new Vect2D(), new Vect2D() };<br />

// final rotated velocity for b[0]

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

Saved successfully!

Ooh no, something went wrong!