Daily Creative Coding

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

円の中で光を反射させる

/**
* Reflection of Light in Circle
*
* @author aa_debdeb
* @date 2016/01/25
*
*/

float lradious = 200;
float sradious = 5;
ArrayList<Particle> particles;

void setup(){
  size(500, 500);
  frameRate(60);
  smooth();
  background(0);
  
  particles = new ArrayList<Particle>();
  for(int i = 0; i < 300; i++){
    particles.add(new Particle());
  }
}

void draw(){
  fill(0, 3);
  noStroke();
  rect(0, 0, width, height);
  translate(width / 2, height / 2);
  stroke(150, 255, 255, 50);
  strokeWeight(2);
  for(Particle particle: particles){
    particle.display();
  }
}

class Particle{

  PVector pos;
  PVector vel;
  
  Particle(){
    float posAng = random(TWO_PI);
    float posDist = random(lradious - sradious);
    pos = new PVector(posDist * cos(posAng), posDist * sin(posAng));
    float velAng = random(TWO_PI);
    float velSize = map(random(1), 0, 1, 1, 2);    
    vel = new PVector(velSize * cos(velAng), velSize * sin(velAng));
  }
  
  void display(){
    PVector nextPos = PVector.add(pos, vel);
    if(nextPos.mag() + sradious >= lradious){
      nextPos.limit(lradious - sradious);
//      float posAng = pos.heading();
//      float velAng = vel.heading();
      float posAng = atan2(pos.y, pos.x);
      float velAng = atan2(vel.y, vel.x);
      
      float velMag = vel.mag();
      vel.x = velMag * cos(2 * posAng - velAng - PI);
      vel.y = velMag * sin(2 * posAng - velAng - PI);     
    }
    line(pos.x, pos.y, nextPos.x, nextPos.y);
    pos = nextPos;
}
  
}