// Simple Particle System // Daniel Shiffman // A class to describe a group of Particles // An ArrayList is used to manage the list of Particles class ParticleSystemFood { ArrayList particles; // An arraylist for all the particles Vector3D ac = new Vector3D(0.0,0.0); Vector3D ve = new Vector3D(0.0,0.0); Vector3D lo = new Vector3D(random(width),random(0,height/2)); ParticleSystemFood() { particles = new ArrayList(); // Initialize the arraylist for (int i = 0; i < maxFood; i++) { lo = new Vector3D(random(width),random(0,height/2)); particles.add(new Food(ac,ve,lo,random(8,13))); } } void run() { // Cycle through the ArrayList backwards b/c we are deleting for (int i = particles.size()-1; i >= 0; i--) { Food f = (Food) particles.get(i); updateParticle(f); if (f.dead() == true){ particles.remove(i); } } } int total(){ return particles.size(); } void updateParticle(Food f){ //Attraction between things for (int j = 0; j < particles.size(); j++) { // For every Thing t[j] Food fj = (Food) particles.get(j); Vector3D k; k = fj.getLoc(); nx = k.getX(); ny = k.getY(); if (f.getX() != nx && f.getY() != ny) { // Make sure we are not calculating gravtional pull on oneself Vector3D force = f.calcGravForce(fj); // Use the function we wrote above f.add_force(force); // Add the force to the object to affect its acceleration } } //Add forces to contain objects within screen if (f.getY() > height/2 - 30){ f.add_force(new Vector3D(0,-5)); } else if (f.getY() < 0){ f.add_force(new Vector3D(0,1)); } if (f.getX() > width) { f.add_force(new Vector3D(-1,0)); } else if (f.getX() < 0) f.add_force(new Vector3D(1,0)); else { f.add_force(new Vector3D(random(-1,1),random(-5,5))); } //Things follow mouse if (mousePressed) { Vector3D m = new Vector3D(mouseX,mouseY); Vector3D diff = Vector3D.sub(m,f.getLoc()); diff.normalize(); float factor = 1.0; // Magnitude of Acceleration (not increasing it right now) diff.mult(factor); f.setAcc(diff); } f.go(); // Implement the rest of the object's functionality } float getX(int i){ Food fj = (Food) particles.get(i); return fj.getX(); } float getY(int i){ Food fj = (Food) particles.get(i); return fj.getY(); } Food getParticle(int i){ Food fj = (Food) particles.get(i); return fj; } void addParticle(int x) { for (int i = 0; i < x; i++){ lo = new Vector3D(random(width),random(0,height/2)); particles.add(new Food(ac,ve,lo,random(8,13))); } } void remParticle(int i){ if (particles.size() > 1){ Food f = (Food) particles.get(i); f.die(); } } void delParticle(int i){ particles.remove(i); } void addParticle(Food f) { particles.add(f); } // A method to test if the particle system still has particles boolean dead() { if (particles.isEmpty()) { return true; } else { return false; } } }