読者です 読者をやめる 読者になる 読者になる

Daily Creative Coding

元「30 min. Processing」。毎日、Creative Codingします。

小さな虫の集まりみたいなパーティクル

/**
* Flies
*
* @author aa_debdeb
* @date 2016/01/30
*/

ArrayList<Particle> particles;

void setup(){
  size(300, 300);
  
  particles = new ArrayList<Particle>();
  for(int i = 0; i < 1000; i++){
    particles.add(new Particle());
  } 
}

void draw(){
  background(0);
  noStroke();
  fill(255, 100);
  for(Particle particle: particles){
    particle.display();
    particle.update();
  }
  
  
}

class Particle{

  PVector position, velocity;
  
  Particle(){
    position = new PVector(random(width), random(height));
    float velAng = map(random(1), 0, 1, 0, TWO_PI);
    float velMag = map(random(1), 0, 1, 0, 2);
    velocity = new PVector(velMag * cos(velAng), velMag * sin(velAng));
  }
  
  void display(){
    ellipse(position.x, position.y, 4, 4);
  }
  
  void update(){
    PVector acceleration = new PVector(0, 0.05);
    if(random(1) < 0.1){
      float accAng = map(random(1), 0, 1, 0, TWO_PI);
      float accMag = map(random(1), 0, 1, 0, 5);
      PVector acc = new PVector(accMag * cos(accAng), accMag * sin(accAng));
      acceleration.add(acc);
    }
    velocity.add(acceleration);
    velocity.limit(2);
    position.add(velocity);
    if(position.x <= 0){
      position.x = 0;
      velocity.mult(0.95);
      velocity.x *= -1;
    }
    if(position.x >= width){
      position.x = width;
      velocity.mult(0.95);
      velocity.x *= -1;
    }
    if(position.y <= 0){
      position.y = 0;
      velocity.mult(0.95);
      velocity.y *= -1;
    }
    if(position.y >= height){
      position.y = height;
      velocity.mult(0.95);
      velocity.y *= -1;
    }
  }  
}