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

Daily Creative Coding

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

マウスの動きをパーティクルで可視化する

/**
* mouse impact
*
* @author aa_debdeb
* @date 2016/12/08
*/

float historySize = 5;
ArrayList<PVector> mouseVelocities;
ArrayList<Particle> particles;

void setup(){
  size(640, 640);
  noStroke();
  fill(255);
  mouseVelocities = new ArrayList<PVector>();
  particles = new ArrayList<Particle>();
}

void draw(){
  background(0);
  ArrayList<Particle> nextParticles = new ArrayList<Particle>();
  for(Particle p: particles){
    p.display();
    p.update();
    if(!p.isBlowedOut()){
      nextParticles.add(p);
    }
  }
  particles = nextParticles;

//  PVector mv = new PVector(mouseX - pmouseX, mouseY, pmouseY);
  mouseVelocities.add(new PVector(mouseX - pmouseX, mouseY - pmouseY));
  if(mouseVelocities.size() > historySize){
    mouseVelocities.remove(0);
  }
  if(mouseVelocities.size() == historySize){
    PVector acc = new PVector(0, 0);
    for(int i = 0; i < mouseVelocities.size() - 1; i++){
      acc.add(PVector.sub(mouseVelocities.get(i + 1), mouseVelocities.get(i)));
    }
    acc.div(mouseVelocities.size() - 1);
    float pNum = acc.mag() * 4.0;
    for(int i = 0; i < pNum; i++){
      PVector vel = PVector.mult(acc, -1);
      vel.limit(5.0);
      float randVelSize = random(0, vel.mag());
      float randVelAng = random(TWO_PI);
      PVector randVel = new PVector(randVelSize * cos(randVelAng), randVelSize * sin(randVelAng));
      vel.add(randVel);
      particles.add(new Particle(vel));
    }
  }
}

class Particle {
  
  PVector loc, vel;
  float size;
  
  Particle(PVector _vel){
    loc = new PVector(mouseX, mouseY);
    vel = _vel;
    size = random(1, 3);
  }
  
  void display(){
    ellipse(loc.x, loc.y, size, size);
  }
  
  void update(){
    loc.add(vel);
    vel.mult(0.95);
    size *= 0.95;
  }
  
  boolean isBlowedOut(){
    return size < 0.1;
  }
  
}
f:id:aa_debdeb:20161201072447j:plain