Daily Creative Coding

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

円の中での反射

/**
* Reflection in Circle
*
* @author aa_debdeb
* @date 2016/01/24
*
*/

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

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

void draw(){
  background(255);
  translate(width / 2, height / 2);
  noFill();
  stroke(255, 0, 0);
  ellipse(0, 0, lradious * 2, lradious * 2);
  for(Particle particle: particles){
    particle.display();
    particle.update();
  }
}

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, 5, 10);    
    vel = new PVector(velSize * cos(velAng), velSize * sin(velAng));
  }
  
  void display(){
    ellipse(pos.x, pos.y, sradious * 2, sradious * 2);
  }
  
  void update(){
    pos.add(vel);
    if(pos.mag() + sradious >= lradious){
      pos.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);     
    }
  } 
}