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

Daily Creative Coding

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

重ならないように回転する球

ランダム
/**
* cycling of balls
*
* @author aa_debdeb
* @date 2016/08/26
*/

color bg;
ArrayList<Spin> spins;

void setup(){
  size(500, 500);
  initialize();
}

void mousePressed(){
  initialize();
}

void initialize(){
  spins = new ArrayList<Spin>();
  for(int i = 0; i < 10000; i++){
    Spin newSpin = new Spin();
    boolean isOverlapped = false;
    for(Spin spin: spins){
      float d = PVector.dist(newSpin.center, spin.center);
      if(d < newSpin.radious + spin.radious + newSpin.size / 2 + spin.size / 2){
        isOverlapped = true;
        break;
      }
    } 
    if(!isOverlapped){
      spins.add(newSpin);
    }
  }
  noStroke();
  fill(random(255), random(255), random(255));
  bg = color(random(255), random(255), random(255));
}

void draw(){
  background(bg);
  for(Spin spin: spins){
    spin.display();
    spin.update();
  }
}

class Spin{
  
  PVector center;
  float angle;
  float angleSpeed;
  float radious;
  float size;
  
  Spin(){
    center = new PVector(random(width), random(height));
    angle += random(TWO_PI);
    angleSpeed = random(-PI / 16, PI / 16); 
    float v = random(1);
    radious = map(v, 0, 1, 2, 10);
    size = map(v, 0, 1, 15, 50);
  }
  
  void display(){
    float x = center.x + radious * cos(angle);
    float y = center.y + radious * sin(angle);
    ellipse(x, y, size, size);
  }
  
  void update(){
    angle += angleSpeed;
    if(angle < 0){
      angle += TWO_PI;
    }
    if(angle >= TWO_PI){
      angle -= TWO_PI;
    }
  }
  
}
f:id:aa_debdeb:20160822183930j:plain