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.

Example 23-4: Super fancy ArrayList and rectangle particle system<br />

// Declaring a global variable of type ArrayList<br />

ArrayList particles;<br />

// A "Rectangle" will suck up particles<br />

Rectangle blackhole;<br />

void setup() {<br />

size(200,200);<br />

blackhole = new Rectangle(50,150,100,25);<br />

particles = new ArrayList();<br />

smooth();<br />

}<br />

void draw() {<br />

background(255);<br />

// Displaying the Rectangle<br />

stroke(0);<br />

fill(175);<br />

rect(blackhole.x, blackhole.y, blackhole.width,blackhole.height);<br />

// Add a new particle at mouse location<br />

particles.add(new Particle(mouseX,mouseY));<br />

// Loop through all Particles<br />

for (int i = particles.size() – 1; i > = 0; i – – ) {<br />

Particle p = (Particle) particles.get(i);<br />

p.run();<br />

p.gravity();<br />

p.display();<br />

if (blackhole.contains(p.x,p.y)) {<br />

p.s<strong>to</strong>p();<br />

}<br />

if (p.finished()) {<br />

particles.remove(i);<br />

}<br />

}<br />

}<br />

// A simple Particle Class<br />

class Particle {<br />

float x;<br />

float y;<br />

float xspeed;<br />

float yspeed;<br />

float life;<br />

// Make the Particle<br />

Particle(float tempX, float tempY) {<br />

x = tempX;<br />

y = tempY;<br />

xspeed = random(–1,1);<br />

yspeed = random(–2,0);<br />

life = 255;<br />

}<br />

fi g. 23.6<br />

Java 433<br />

If the Rectangle contains the location of the<br />

Particle, s<strong>to</strong>p the Particle from moving.

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

Saved successfully!

Ooh no, something went wrong!