Daily Creative Coding

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

似非流体

f:id:aa_debdeb:20160804175818j:plain
/**
* fake fluid
*
* @author aa_debdeb
* @date 2016/08/09
*/

int cellNum = 200;
float cellSize = 2;
ArrayList<Particle> particles;

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

void draw(){
  background(0, 0, 139);
  if(mousePressed){
    PVector mouse = new PVector(mouseX, mouseY);
    PVector pmouse = new PVector(pmouseX, pmouseY);
    PVector disp = PVector.sub(mouse, pmouse);
    disp.normalize();
    disp.mult(0.3);
    for(Particle p: particles){
      float d = PVector.dist(p.loc, mouse);
      if(d < 100){
        p.vel.add(PVector.mult(disp, (100 - d) / 100.0));  
      }    
    }
  }
  int[][] cells = new int[cellNum][cellNum];
  for(Particle p: particles){
    cells[int(p.loc.x / cellSize)][int(p.loc.y / cellSize)] += 1;
    p.update();
  }
  for(int x = 0; x < cellNum; x++){
    for(int y = 0; y < cellNum; y++){
      float alpha = map(cells[x][y], 0, 10, 0, 255);
      fill(0, 255, 127, alpha);
      noStroke();
      rect(x * cellSize, y * cellSize, cellSize, cellSize);
    }
  }
}

class Particle{
  PVector loc, vel;
  
  Particle(){
    loc = new PVector(random(width), random(height));
    float velSize = random(2);
    float velAngle = random(TWO_PI);
    vel = new PVector(velSize * cos(velAngle), velSize * sin(velAngle));
  }
  
  void update(){
    float velSize = random(0.05);
    float velAngle = random(TWO_PI);
    vel.add(new PVector(velSize * cos(velAngle), velSize * sin(velAngle)));
    vel.mult(0.99);
    loc.add(vel);
    if(loc.x < 0){
      vel.x *= -1;
      loc.x += vel.x;
    }
    if(loc.x >= width){
      vel.x *= -1;
      loc.x += vel.x;
    }
    if(loc.y < 0){
      vel.y *= -1;
      loc.y += vel.y;
    }
    if(loc.y >= height){
      vel.y *= -1;
      loc.y += vel.y;
    }
  }
  
}