Daily Creative Coding

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

パーリンノイズによるパーティクルの流れ 3D

/**
* flow in 3D box
*
* @author aa_debdeb
* @date 2016/04/30
*/

float depth = 500;
PVector[] nOffset;
float nScale = 0.01;
float stepSize = 3;

ArrayList<Particle> particles;

void setup(){
  size(500, 500, P3D);
  nOffset = new PVector[3];
  for(int i = 0; i < 3; i++){
    nOffset[i] = new PVector(random(10000), random(10000), random(10000));
  }
  particles = new ArrayList<Particle>();
  for(int i = 0; i < 100; i++){
    particles.add(new Particle());
  }
  
  noFill();
  background(0);
}

void draw(){
  pushMatrix();
  translate(width / 2 + 50, height / 2 - 50, -250);
  rotateX(-PI / 6);
  rotateY(PI / 3);
  stroke(255, 0, 136, 32);
  for(Particle p: particles){
    p.update();
  }
  stroke(32);
  box(width, height, depth);
  popMatrix();
}

void mousePressed(){
  for(int i = 0; i < 3; i++){
    nOffset[i] = new PVector(random(10000), random(10000), random(10000));
  }
  particles = new ArrayList<Particle>();
  for(int i = 0; i < 100; i++){
    particles.add(new Particle());
  }
  background(0);
}

class Particle{
  
  PVector pos;
  
  Particle(){
    pos = new PVector(random(width), random(height), random(depth));
  }
  
  void update(){
    float x = pos.x + map(noise(nOffset[0].x + pos.x * nScale, nOffset[0].y + pos.y * nScale, nOffset[0].z + pos.z * nScale), 0, 1, -stepSize, stepSize);  
    float y = pos.y + map(noise(nOffset[1].x + pos.x * nScale, nOffset[1].y + pos.y * nScale, nOffset[1].z + pos.z * nScale), 0, 1, -stepSize, stepSize);  
    float z = pos.z + map(noise(nOffset[2].x + pos.x * nScale, nOffset[2].y + pos.y * nScale, nOffset[2].z + pos.z * nScale), 0, 1, -stepSize, stepSize);  
    PVector npos = new PVector(x, y, z);
    pushMatrix();
    translate(-width / 2, -height / 2, -depth / 2);
    line(pos.x, pos.y , pos.z, npos.x, npos.y, npos.z);
    popMatrix();
    if((0 <= npos.x && npos.x < width && 0 <= npos.y && npos.y < height && 0 <= npos.z && npos.z < depth) &&
        (random(1) < 0.995)){
      pos = npos;
    } else {
      pos = new PVector(random(width), random(height), random(depth));      
    }
  }
}