日常の進捗

主に自分のための,行為とその習慣化の記録

六角形のグリッドを敷き詰める

毎回TweakModeでなんだかなという感じで雰囲気で組んでいた六角形のグリッドを15行コーディングの1つに入れたいなと思い、きちんと組んでみることにした。図形の平面充填(テセレーション)は研究されてて資料が多い。六角形のグリッドは以下のページが参考になった。敷き詰めるグリッドのXY方向にそれぞれ敷き詰める六角形の移動分のピクセル三角関数で計算する。本末転倒、15行で書くのはちょっと無理かもしれない。

Hexagonal Grids

コード

float grid = 20;
boolean flag = true;
void setup() {
  size(960, 540);
  colorMode(HSB, 360, 100, 100);
}

void draw() {
  translate(width/2, height/2);
  for (float y = -height / 2 - grid; y < height / 2 + grid; y += grid + grid / 2) {
    for (float x = -width / 2 - grid; x < width / 2 + grid; x += grid * sqrt(3)) {
      PVector location;
      if (flag) {
        location = new PVector(x, y);
      } else {
        location = new PVector(x + (grid * sqrt(3) / 2), y);
      }
      float distance = PVector.dist(location, new PVector(0, 0));
      color c = color(abs(map(distance, 0, sqrt(sq(width/2)+sq(height/2)), 0, 360)-frameCount*5)%360, 80, 100);
      stroke(0, 0, 100);
      fill(c);
      pushMatrix();
      translate(location.x, location.y);
      rotate(PI/6);
      beginShape();
      for (float angle = 0; angle < 360; angle += 360/6) {
        float hexX = cos(radians(angle)) * grid;
        float hexY = sin(radians(angle)) * grid;
        vertex(hexX, hexY);
      }
      endShape(CLOSE);
      popMatrix();
    }
    flag = !flag;
  }
}