/* simple_particles.pde - nik hanselmann nikhan@gmail.com This code shows how to create simple replusion forces for particles. The software is provided with no license, do whatever you want with it. Just don't do Bad Things(tm). For fun, hold down the mouse button in the space place without moving your mouse, wait for all the particles to accumulate in that space, then move your mouse. Watch the fireworks! */ particle[] p = new particle[200]; int next_p = 0; // this is our index for our particle array float repulse = 20; // keep everything spaced out 15 pixels float particle_size = 5; // make the particles 5px wide class particle{ PVector position; // (x,y,z) vector of our particle. we only use the first two PVector accel; // the particle's acceleration particle repulse(particle cp){ /*here we recieve a particle and compare it to the current particle. we return the vector of the recieved particle and add it to its acceleration.*/ PVector distance = new PVector(0,0); distance.set(cp.position); distance.sub(position); PVector origin = new PVector(0,0); if(distance.dist(origin) < repulse){ distance.normalize(); cp.accel.add(distance); } return cp; } void reset(){ position = new PVector(0,0); accel = new PVector(0,0); } } void setup(){ size(400,400); for(int i = 0; i < p.length; i++){ p[i] = new particle(); p[i].reset(); } smooth(); noStroke(); } void draw(){ background(0); for(int i = 0; i < p.length; i++){ p[i].accel.set(0,0,0); // reset all vectors every iteration } if(mousePressed == true){ if(next_p >= p.length){ //don't go beyond the bounds of the array! next_p = 0; } p[next_p].position.set(mouseX,mouseY,0); next_p++; } for(int i = 0; i < p.length; i++){ for(int j = 0; j < p.length; j++){ /*for every particle i, we compare it the the rest of the particles of the same array, j. We add all the forces together and then compute them*/ p[i] = p[j].repulse(p[i]); } p[i].position.add(p[i].accel); // add the acceleration array to the particle's position ellipse(p[i].position.x, p[i].position.y, particle_size, particle_size); } }