Daily Creative Coding

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

マウスでカメラを操作する

/**
* camera manipulation
*
* @author aa_debdeb
* @date 2016/05/21
*/

Cam cam;
ArrayList<Obj> objs;

void setup(){
  size(500, 500, P3D);
  cam = new Cam();
  objs = new ArrayList<Obj>();
  for(int i = 0; i < 100; i++){
    objs.add(new Obj());
  }
}

void draw(){
  background(32);
  lights();
  translate(width / 2, height / 2, 0);
  cam.setCamera();
  cam.update();
  for(Obj obj: objs){
    obj.display();
  }
}

class Cam{
  PVector eye;
  float  cRadious;
  float cRadian;
  float eyeSpeed = 5.0;
  float cRadianSpeed = PI / 64;
  Cam(){
    eye = new PVector(0, 0, 0);  
    cRadious = 50;
    cRadian = random(TWO_PI);
  }
  
  void update(){
    if(mouseX > 2 * width / 3){
      cRadian += cRadianSpeed;
      if(cRadian >= TWO_PI){
        cRadian -= TWO_PI;
      }
    } else if(mouseX < width / 3){
      cRadian -= cRadianSpeed;
      if(cRadian < 0){
        cRadian += TWO_PI;
      }
    }
    if(mousePressed){
      eye.x += eyeSpeed * cos(cRadian);
      eye.z += eyeSpeed * sin(cRadian);
    }
  }
  
  void setCamera(){
    float cx = eye.x + cRadious * cos(cRadian);
    float cy = eye.y; 
    float cz = eye.z + cRadious * sin(cRadian);
    camera(eye.x, eye.y, eye.z, cx, cy, cz, 0, 1, 0);
  }
}  

class Obj{
  PVector pos;
  float size;
  boolean isSphere;
  color c;
  Obj(){
    float r = map(pow(random(1), 1.0 / 2), 0, 1, 0, 1000);
    float a1 = random(PI);
    float a2 = random(TWO_PI);    
    float x = r * cos(a1) * cos(a2);
    float y = r * cos(a1) * sin(a2);
    float z = r * sin(a1);
    pos = new PVector(x, y, z);
    size = random(50, 100);
    isSphere = random(1) < 0.5;
    c = color(random(255), 255, random(255));
  }
  void display(){
    pushMatrix();
    translate(pos.x, pos.y, pos.z);
    fill(c);
    noStroke();
    if(isSphere){
      sphere(size);
    } else {
      box(size);
    }
    popMatrix();  
  }
}