P5.js Study 036

Generative Design with p5.js / Sketch P_2_2_5_01 を試しながらアレンジ。
元ネタ:https://editor.p5js.org/generative-design/sketches/P_2_2_5_01

ロジックのポイント

ランダムな円を描いて、他の円と重なっているなら、1ピクセルずつ小さくしながら、重ならない最大の円を見つける。

  var intersection = false;
  for (var newR = maxRadius; newR >= minRadius; newR--) {
    for (var i = 0; i < circles.length; i++) {
      var d = dist(newX, newY, circles[i].x, circles[i].y);
      intersection = d < circles[i].r + newR;
      if (intersection) {
        break;
      }
    }
    if (!intersection) {
      circles.push(new Circle(newX, newY, newR));
      break;
    }
  }

円一つごとに、すべての円と接するかどうか(中心間の距離が半径の和+1より小さいか。1足しているのは誤差対策だろう)を調べて、接するならば中心間に直線を引く。

      var closestCircle;
      for (var j = 0; j < circles.length; j++) {
        var d = dist(circles[i].x, circles[i].y, circles[j].x, circles[j].y);
        if (d <= circles[i].r + circles[j].r + 1) {
          closestCircle = circles[j];
          break;
        }
      }
      if (closestCircle) {
        stroke(100, 230, 100);
        strokeWeight(0.75);
        line(circles[i].x, circles[i].y, closestCircle.x, closestCircle.y);
      }

マウスで指定した範囲に円を描いてくれる機能も面白い。

Leave a comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です