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

Daily Creative Coding

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

触れると膨らむ円

/**
 * expanding circles 
 *
 * @author aadebdeb
 * @date 2017/03/13
 */

var eventManager;

function setup() {
  createCanvas(windowWidth, windowHeight);
  frameRate(30);
  eventManager = new EventManager();
  for (var i = 0; i < 100; i++) {
    eventManager.add(new Circle());
  }
}

function draw() {
  eventManager.render();
  eventManager.notify();
  eventManager.update();
}

function EventManager() {
  this.circles = [];
}

EventManager.prototype = {

  render: function() {
    background(255, 255, 250);
    noStroke();
    fill(66, 64, 72);
    for (var i = 0; i < this.circles.length; i++) {
      this.circles[i].render();
    }
  },
  
  notify: function() {
    var mouse = createVector(mouseX, mouseY)
    for (var i = 0; i < this.circles.length; i++) {
      var c = this.circles[i];
      var d = mouse.dist(c.loc);
      if (!c.hasExpaned && !c.isExpanding && d < c.radius) {
        c.startExpanding();
      }
    }
  },
  
  update: function() {
    for (var i = 0; i < this.circles.length; i++) {
      this.circles[i].update(this.circles);
    }
  },
  
  add: function(circle) {
    for (var i = 0; i < this.circles.length; i++) {
      var other = this.circles[i];
      var d = circle.loc.dist(other.loc);
      if (d < circle.radius + other.radius) {
        return;
      }
    }
    this.circles.push(circle); 
  }
}



function Circle() {
  this.isExpanding = false;
  this.hasExpaned = false;
  this.radius = random(20, 50);
  this.expandingSpeed = random(0.2, 0.5);
  this.loc = createVector(random(0, width), random(0, height)); 
}

Circle.prototype = {
  render: function() {
    ellipse(this.loc.x, this.loc.y, this.radius * 2, this.radius * 2);
  },
  
  update: function(circles) {
    if (this.isExpanding) {
      this.radius += this.expandingSpeed;
      for (var i = 0; i < circles.length; i++) {
        var other = circles[i];
        if (this !== other && this.loc.dist(other.loc) <= this.radius + other.radius) {
          this.isExpanding = false;
          this.hasExpaned = true;
        }
      }
    }
  },
  
  startExpanding: function () {
    this.isExpanding = true;
  }
}
f:id:aa_debdeb:20170312202529j:plain