Daily Creative Coding

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

二色のメタボール

/**
* two-color metaballs
*
* @author aa_debdeb
* @date 2016/08/07
*/

int num = 20;
ArrayList<Particle> particles;
int cellNum = 200;
float cellSize = 2;
float[][] cells;
color c1 = color(255, 140, 0);
color c2 = color(0, 242, 255);

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

void draw(){
  for(int y = 0; y < cellNum + 1; y++){
    for(int x = 0; x < cellNum + 1; x++){
      PVector c = new PVector(x * cellSize + cellSize / 2, y * cellSize + cellSize / 2);
      cells[x][y] = 0.0;
      for(Particle p: particles){
        if(p.positive){
          cells[x][y] += p.radious / PVector.sub(c, p.loc).mag();
        } else {
          cells[x][y] -= p.radious / PVector.sub(c, p.loc).mag();        
        }
      }
    }
  }
  noStroke();
  for(int y = 0; y < cellNum; y++){
    for(int x = 0; x < cellNum; x++){
      float r = map(cells[x][y], -2, 2, red(c1), red(c2));
      float g = map(cells[x][y], -2, 2, green(c1), green(c2));
      float b = map(cells[x][y], -2, 2, blue(c1), blue(c2));      
      fill(r, g, b);
      rect(x * cellSize, y * cellSize, cellSize, cellSize);
    }
  }
  for(Particle p: particles){
    p.update();
  }
}

class Particle{
  
  float radious;
  PVector loc, vel;
  boolean positive;
  
  Particle(){
    radious = random(50, 100);
    loc = new PVector(random(radious, width - radious), random(radious, height - radious));
    float velSize = random(1, 3);
    float velAng = random(TWO_PI);
    vel = new PVector(velSize * cos(velAng), velSize * sin(velAng));
    positive = random(1) < 0.5 ? true: false;
  }
  
  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;
    }
  }
}
f:id:aa_debdeb:20160802092316j:plain