Tut­o­r­i­a­l 21 - The par­t­i­c­l­e system

by Giselle Gray

Playing with velocity

  • Show Sketch
/** @peep sketchcode */
int NUM_PARTICLES = 100;
Particle[] particles;
 
void setup() {
  size(400, 400);
  PVector centre = new PVector(width/2, height/2, 0);
  particles = new Particle[NUM_PARTICLES];  
  for (int i = 0; i < particles.length; i++) {
    particles[i] = new Particle(centre);
  }
}
 
void update() {
  for (int i = 0; i < particles.length; i++) {
    particles[i].update();
  }
}
 
void draw() {
  update();
  background(255);
  for (int i = 0; i < particles.length; i++) {
    PVector l = particles[i].location;
    ellipse(l.x, l.y, 20, 20);
    PVector v = particles[i].velocity;
    line(l.x, l.y, l.x + v.x*10, l.y + v.y*10);
  }
}
 
class Particle {
  PVector location;
  PVector velocity;
  PVector acceleration;
 
  Particle(PVector _location) {
    location = _location.get(); // make a copy of given location using get()
    velocity = new PVector(random(-25, 25), random(-25, 25));
    acceleration = new PVector(0, 0.1);
  }
 
  void update() {
    velocity.add(acceleration);
    location.add(velocity);
  }
}
  • Show Sketch
/** @peep sketchcode */
int NUM_PARTICLES = 100;
ParticleSystem particle_system;
 
void setup() {
  size(400, 400);
  PVector centre = new PVector(width/2, height/2, 0);
  particle_system = new ParticleSystem(centre, NUM_PARTICLES);
}
 
void update() {
  particle_system.update();
}
 
void draw() {
  update();
  background(255);
  for (int i = 0; i < particle_system.particles.length; i++) {
    PVector l = particle_system.particles[i].location;
    ellipse(l.x, l.y, 20, 20);
    PVector v = particle_system.particles[i].velocity;
    line(l.x, l.y, l.x + v.x*10, l.y + v.y*10);
  }
}
 
class Particle {
  PVector location;
  PVector velocity;
  PVector acceleration;
  float time_to_live;
 
  Particle(PVector _location) {
    location = _location.get(); // make a copy of given location using get()
    velocity = new PVector(random(-5, 5), random(-5, 5));
    acceleration = new PVector(0, 0.1);
    time_to_live = random(100, 200);
  }
 
  void update() {
    velocity.add(acceleration);
    location.add(velocity);
    time_to_live -= 1;
  }
 
  boolean dead() {
    return (time_to_live <= -5);
  }
}
 
class ParticleSystem {
  PVector location;
  Particle[] particles;
 
  ParticleSystem(PVector _location, int _num_particles) {
    location = _location.get();
    particles = new Particle[_num_particles];
    for (int i = 0; i < particles.length; i++) {
      particles[i] = new Particle(location);
    }
  }
 
  void update() {
    for (int i = 0; i < particles.length; i++) {
      particles[i].update();
      if (particles[i].dead()) {
        particles[i] = new Particle(location);
      }
    }
  }
}

Comments

Nobody has said anything yet.