Daily Creative Coding

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

メタボール(低解像度版)

/**
* metaballs (low resolution)
* 
* @author aa_debdeb
* @date 2016/06/24
*/

int num = 10;
ArrayList<Particle> particles;
int cellNum = 100;
float cellSize = 5;
float[][] cells;

void setup(){
  size(500, 500);
  cells = new float[cellNum + 1][cellNum + 1];
  particles = new ArrayList<Particle>();
  for(int i = 0; i < num; i++){
    particles.add(new Particle());
  }
}

void draw(){
  background(0, 0, 26);
  for(int y = 0; y < cellNum + 1; y++){
    for(int x = 0; x < cellNum + 1; x++){
      PVector c = new PVector(x * cellSize, y * cellSize);
      cells[x][y] = 0.0;
      for(Particle p: particles){
        cells[x][y] += p.radious / PVector.sub(c, p.loc).mag();
      }
    }
  }
  for(int y = 0; y < cellNum; y++){
    for(int x = 0; x < cellNum; x++){
      float v = (cells[x][y] + cells[x + 1][y] + cells[x][y + 1] + cells[x + 1][y + 1]) / 4.0;
      float alpha = map(v, 0.8, 1.2, 0, 255);
      noStroke();
      fill(255, 236, 230, alpha);
      rect(x * cellSize, y * cellSize, cellSize, cellSize);
    }
  }
  for(Particle p: particles){
    p.update();
  }
}

class Particle{
  
  float radious;
  PVector loc, vel;
  
  Particle(){
    radious = random(10, 20);
    loc = new PVector(random(radious, width - radious), random(radious, height - radious));
    float velSize = random(2, 5);
    float velAng = random(TWO_PI);
    vel = new PVector(velSize * cos(velAng), velSize * sin(velAng));
  }
  
  void update(){
    loc.add(vel);
    if(loc.x < radious){
      vel.x *= -1;
      loc.x += vel.x;
    }
    if(loc.x >= width - radious){
      vel.x *= -1;
      loc.x += vel.x;
    }
    if(loc.y < radious){
      vel.y *= -1;
      loc.y += vel.y;
    }
    if(loc.y >= height - radious){
      vel.y *= -1;
      loc.y += vel.y;
    }
  }
}