Daily Creative Coding

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

パーティクルの軌跡

/**
* Trail of Particles
*
* @author aa_debdeb
* @date 2016/02/28
*/

int PARTICLE_NUM = 1000;
float PARTICLE_RADIOUS = 1.5;
float PARTICLE_MAX_SPEED = 10.0;
float PARTICLE_MAX_ACCELERATION = 1.0;
float PARTICLE_SPEED_VARIANT = 0.1;

ArrayList<Particle> particles;

PVector inPos, outPos;

void setup(){
  size(500, 500);
  background(0);
  particles = new ArrayList<Particle>();
  
  inPos = new PVector(0, 0);
  outPos = new PVector(0, 0);
}

void mousePressed(){
  saveFrame("images/image.jpg");
}

void draw(){
  
  inPos.x = width / 2 + 200 * cos(frameCount * 0.05);
  inPos.y = height / 2 + 200 * sin(frameCount * 0.05);
  outPos.x = width / 2 + 200 * cos(frameCount * 0.04);
  outPos.y = height / 2 + 200 * sin(frameCount * 0.04);
  
  if(frameCount % 3 == 1 && particles.size() < PARTICLE_NUM){
    Particle particle = new Particle();
    particle.position = new PVector(inPos.x, inPos.y);
    particles.add(particle);
  } 
  
  noStroke();
  fill(0, 10);
  rect(0, 0, width, height);
  
  ArrayList<Particle> nextParticles = new ArrayList<Particle>();
  for(Particle particle: particles){
    particle.display();
    if(PVector.dist(particle.position, outPos) >= 15){
      particle.update(); 
      nextParticles.add(particle);     
    }
  }
  particles = nextParticles;
}

class Particle{
  
  PVector position;
  PVector velocity;
  
  Particle(){
    position = new PVector(random(width), random(height));
    setRandomVelocity();
  }
  
  void setRandomVelocity(){
    velocity = new PVector(random(2) - 1.0, random(2) - 1.0);
    velocity.normalize();
    velocity.mult(random(PARTICLE_MAX_SPEED * 2) - PARTICLE_MAX_SPEED);
  }
  
  void display(){
    noStroke();
    fill(160);
    ellipse(position.x, position.y, PARTICLE_RADIOUS * 2, PARTICLE_RADIOUS * 2);
  }
  
  void update(){
    PVector direction = PVector.sub(outPos, position);
    direction.normalize();
    PVector acceleration = PVector.mult(direction, PARTICLE_MAX_ACCELERATION);
    velocity.add(acceleration);
    PVector velocityVariant = new PVector(random(2) - 1.0, random(2) - 1.0);
    velocityVariant.normalize();
    velocityVariant.mult(PARTICLE_SPEED_VARIANT);
    velocity.add(velocityVariant);
    velocity.limit(PARTICLE_MAX_SPEED);
    position.add(velocity);
  }
  
}