Daily Creative Coding

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

マウスによるボックスの回転

/**
* box rotation by mouse
* 
* @author aa_debdeb
* @date 2016/04/21
*/

float maxVel = PI / 16;
float velStep = PI / 64;

color c1 = color(255, 20, 146);
color c2 = color(51, 4, 29);

ArrayList<Box> boxes;

void setup(){
  size(640, 640, P3D);
  
  stroke(128);
  
  boxes = new ArrayList<Box>();
  for(int w = 0; w <= width; w += 40){
    for(int h = 0; h <= height; h += 40){
      boxes.add(new Box(new PVector(w, h)));
    }
  }
}

void draw(){
  background(255, 230, 243);
  lights();
  
  for(Box box: boxes){
    box.update();
    box.display();  
  }
}

class Box{
  
  PVector pos, rad, vel;
  
  Box(PVector pos){
    this.pos = pos;
    rad = new PVector(0, 0);
    vel = new PVector(0, 0);
  }
  
  void update(){
    vel.mult(0.995);
    if(mousePressed){
      PVector mouse = new PVector(mouseX - pmouseX, pmouseY - mouseY);
      vel.x += map(mouse.x, -width, width, -velStep, velStep);
      constrain(vel.x, -maxVel, maxVel);
      vel.y += map(mouse.y, -height, height, -velStep, velStep);
      constrain(vel.y, -maxVel, maxVel);
    }
    rad.x += vel.x;
    rad.y += vel.y; 
  }
  
  void display(){
    pushMatrix();
    translate(pos.x, pos.y);
    rotateY(rad.x);
    rotateX(rad.y);
    float energy = pow(map(vel.mag(), 0, maxVel * sqrt(2), 0, 1), 1.0 / 3);
    float r = red(c1) * energy + red(c2) * (1 - energy);
    float g = green(c1) * energy + green(c2) * (1 - energy);
    float b = blue(c1) * energy + blue(c2) * (1 - energy);    
    fill(r, g, b);
    box(map(energy, 0, 1, 10, 40));
    popMatrix();
  }
  
}