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

Daily Creative Coding

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

パーティクルによる図形

/**
* Shape by Particles
*
* @author aa_debdeb
* @date 2016/03/12
*/


int PARTICLE_NUM = 15;
float PARTICLE_RADIOUS = 1.5;
float PARTICLE_MAX_SPEED = 6.0;
float PARTICLE_MAX_ACCELERATION = 0.4;
float PARTICLE_IMPACT_SPEED = 300;
float PARTICLE_SPEED_VARIANT = 0.5;

Particle[] particles;

void setup(){
  size(500, 500);
  frameRate(30);

  particles = new Particle[PARTICLE_NUM];
  for(int i = 0; i < PARTICLE_NUM; i++){
    particles[i] = new Particle();
  }
 
}

void draw(){
  background(255, 239, 213);

  fill(144, 238, 144);
  noStroke();
  for(int i = 0; i < particles.length - 2; i++){
    PVector p1 = particles[i].position;
    for(int j = i + 1; j < particles.length - 1; j++){
      PVector p2 =particles[j].position;
      for(int k = j + 1; k < particles.length; k++){
        PVector p3 = particles[k].position;
        triangle(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
      }
    }
  }

  stroke(0, 139, 139);
  strokeWeight(3);
  noFill();
  for(Particle particle: particles){
    ellipse(particle.position.x, particle.position.y, 6, 6);
    particle.update();
  }
}

void mousePressed(){
   for(Particle particle: particles){
    particle.impact();
  } 
}

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 impact(){
    velocity = PVector.random2D();
    velocity.normalize();
    velocity.mult(PARTICLE_IMPACT_SPEED);
  }
  
  void display(){
    noStroke();
    fill(160);
    ellipse(position.x, position.y, PARTICLE_RADIOUS * 2, PARTICLE_RADIOUS * 2);
  }
  
  void update(){
    PVector mouse = new PVector(mouseX, mouseY);
    PVector direction = PVector.sub(mouse, 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);
  }
  
}