読者です 読者をやめる 読者になる 読者になる

Daily Creative Coding

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

ばね

/**
* Springs
*
* @author aa_debdeb
* @date 2015/10/11
*/


int SPRING_NUM = 30;
float SPRING_COEFFICNET = 0.01;
PVector center;
ArrayList<Spring> springs;

void setup(){
  size(500, 500);
  smooth();
  frameRate(24);

  center = new PVector(width/2, height/2);

  springs = new ArrayList<Spring>();
  for(int i = 0; i < SPRING_NUM; i++){
    springs.add(new Spring());
  }

}

void draw(){
  background(255);
  for(Spring s: springs){
    s.display();
    s.update();
  }
}

class Spring{
  
  PVector position;
  PVector velocity;
  float normalLength;
  float springLength;
  
  Spring(){
    normalLength = 150;
    springLength = normalLength + random(100);
    float radian = random(TWO_PI);
    position = new PVector(center.x + cos(radian) * springLength, center.y + sin(radian) * springLength); 
    velocity = new PVector(0, 0);
  }
  
  void display(){
    stroke(0);
    strokeWeight(3);
    line(center.x, center.y, position.x, position.y);
    stroke(40);
    strokeWeight(3);
    fill(160);
    ellipse(position.x, position.y, 50, 50);    
  }
  
  void update(){
    float extention = springLength - normalLength;
    PVector direction = PVector.sub(position, center);
    direction.normalize();
    PVector acceleration = PVector.mult(direction, -1.0 * SPRING_COEFFICNET * extention);
    velocity.add(acceleration);
    position.add(velocity);
    springLength = PVector.dist(center, position);
  }

}