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

Daily Creative Coding

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

マウスクリックに反応して移動する円

/**
* rotating circles
*
* @author aa_debdeb
* @date 2016/09/20
*/

float r = 200;
int num = 20;
ArrayList<Particle> particles;
boolean isMoving;
int startTime, endTime;

void setup(){
  size(640, 640);
  particles = new ArrayList<Particle>();
  float angStep = TWO_PI / num;
  for(int i = 0; i < num; i++){
    particles.add(new Particle(i * angStep));
  }
  background(0, 139, 139);
}

void mousePressed(){
  if(!isMoving){
    int movingStep = int(map(mouseX, 0, width, 1, num - 1));
    int movingTime = int(map(mouseY, 0, height, 10, 150));
    startTime = frameCount;
    endTime = frameCount + movingTime;
    for(Particle p: particles){
      p.target = p.angle + movingStep * TWO_PI / num;
    }
    isMoving = true;
  }
}

void draw(){
  fill(0, 139, 139, 70);
  rect(0, 0, width, height);
  translate(width / 2, height / 2);
  rotate(frameCount * 0.001);
  noStroke();
  fill(0);
  for(Particle p: particles){
    p.display();
    p.update();
  }
  if(frameCount == endTime){
    isMoving = false;
    for(Particle p: particles){
      p.angle = p.target;
    }
  }
}

class Particle{

  float angle, target;
  
  Particle(float _angle){
    angle = _angle;    
  }
  
  void display(){
    float x, y;
    if(!isMoving){
      x = r * cos(angle);
      y = r * sin(angle);
    } else {
      float v = float(frameCount - startTime) / ( endTime - startTime);
      x = lerp(r * cos(angle), r * cos(target), v);
      y = lerp(r * sin(angle), r * sin(target), v); 
    }
    stroke(255, 255, 220, 200);
    strokeWeight(5);
    noFill();
    ellipse(x, y, 30, 30);
    noStroke();
    fill(255, 255, 220, 200);
    ellipse(x, y, 20, 20);

  }
  
  void update(){

  }
  
}
f:id:aa_debdeb:20160917235028j:plain