Daily Creative Coding

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

3D空間の奥から向かってくるオブジェクト

/**
* objects from deep
*
* @author aa_debdeb
* @date 2016/05/15
*/

ArrayList<Obj> objs;

void setup(){
  size(500, 500, P3D);
  objs = new ArrayList<Obj>();
  noStroke();
  colorMode(HSB, 360, 100, 100);
}

void draw(){
  background(180, 12, 100);
//  lights();
  float r = width / 2;
  float cx = map(mouseX, 0, width, -width / 2, width / 2);
  float cy = map(mouseY, 0, height, -height / 2, height / 2);
  float cz;
  if(sqrt(sq(cx) + sq(cy)) > r){
    cz = 0;
  } else {
    cz = -sqrt(sq(r) -sq(cx) - sq(cy));
  }
  translate(width / 2, height / 2, 0);
  camera(0, 0, 0, cx, cy, cz, 0, 1, 0);
  ArrayList<Obj> nextObjs = new ArrayList<Obj>();
  for(Obj obj: objs){
    obj.display();
    obj.update();
    if(!obj.isKilled()){
      nextObjs.add(obj);
    }
  }
  objs = nextObjs;
  if(random(1) < 1){
    objs.add(new Obj());
  }
}

class Obj{
  
  PVector pos;
  float size, speed;
  boolean isSphere;
  color c;
  
  Obj(){
    pos = new PVector(random(-width, width), random(-height, height), -3000);
    size = random(20, 100);
    speed = random(10, 100);
    isSphere = random(1) < 0.5; 
    c = color(random(360), 24, 100);   
  }
  
  void display(){
    pushMatrix();
    translate(pos.x, pos.y, pos.z);
    fill(c);
    if(isSphere){
      sphere(size);
    } else {
      box(size);
    }
    popMatrix();
  }
  
  void update(){
    pos.z += speed;
  }
  
  boolean isKilled(){
    return pos.z > 0;
  }
}