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.

float x, y, r = 20;<br />

float speedX = 2, speedY = 2.5;<br />

void setup(){<br />

size(400, 400);<br />

x = width/2;<br />

y = height/2;<br />

noStroke();<br />

smooth();<br />

}<br />

void draw(){<br />

background(0);<br />

x+=speedX;<br />

y+=speedY;<br />

ellipse(x, y, r*2, r*2);<br />

// check wall collisions<br />

if (x > width-r){<br />

x = width-r;<br />

speedX*=-1;<br />

}<br />

else if (x < r){<br />

x = r;<br />

speedX*=-1;<br />

}<br />

else if (y > height-r){<br />

y = height-r;<br />

speedY*=-1;<br />

}<br />

else if (y < r){<br />

y = r;<br />

speedY *=-1;<br />

}<br />

}<br />

This strategy will work fine for orthogonal collisions, when the object bounces off a horizontal<br />

or vertical surface. However, it won’t work for an object hitting an angular or curved<br />

surface, including objects colliding with each other. The next section will show you how to<br />

deal with these cases.<br />

Vectors<br />

To begin to think about these more advanced types of collisions, you need to consider<br />

how an object’s path is controlled by the speed values you increment it by. In the last<br />

example, I incremented x by 2 <strong>and</strong> y by 2.5. Obviously, since y is being increased more<br />

each frame than is x, the object moves on more of a vertical path than a horizontal one.<br />

Since neither speed value was 0, you could also predict that the object would move in<br />

some type of diagonal path. If speedX had been 0, the object would have only moved vertically.<br />

And of course the situation would have been reversed if speedY had been 0.<br />

MOTION<br />

521<br />

11

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

Saved successfully!

Ooh no, something went wrong!