LoginSignup
1
1

More than 5 years have passed since last update.

processingで雪の結晶を作ってみよう

Posted at

はじめに

はじめまして。Adachiです。

今回はProcessingを使って、クリックすると角の数が増えていく雪の結晶のプログラムを公開しようと思います。

注意

ProcessingについてはProcessing3.4のJavaモードを使っています。

code

コードは以下のようになります。

ArrayList<Koch>koch=new ArrayList<Koch>();
ArrayList<Koch>kochSTK=new ArrayList<Koch>();

void setup() {
  size(800, 800);
  strokeWeight(0);
  stroke(#ffffff);
  fill(255);
  noFill();
  int n=6;
  for (int i=0; i<n; i++) {
    float d=i*TWO_PI/n;
    float r=width*0.37;
    koch.add(new Koch(width/2+cos(d)*r, height/2+sin(d)*r, 
      width/2+cos(d+TWO_PI/n)*r, height/2+sin(d+TWO_PI/n)*r));
  }
  noLoop();
}

void mousePressed() {
    redraw();
}

void draw() {
  background(0);

  beginShape();
  for (Koch k : koch) {
    k.update();
    kochSTK.addAll(k.mkKoch());
  }
  endShape();
  koch.clear();
  koch.addAll(kochSTK);
  kochSTK.clear();

  println("step : "+frameCount);
}

public class Koch {
  float sx, sy, ex, ey;
  public Koch(float sx, float sy, float ex, float ey) {
    this.sx=sx;
    this.sy=sy;
    this.ex=ex;
    this.ey=ey;
  }

  public void update() {
    vertex(sx, sy);
    vertex(ex, ey);
  }

  public ArrayList<Koch>mkKoch() {
    ArrayList<Koch>koch=new ArrayList<Koch>();
    float l=sqrt((sq(sx-ex)+sq(sy-ey)))/3;
    float a=atan2(ey-sy, ex-sx)+PI/3;
    float x=lerp(sx, ex, 1./3.);
    float y=lerp(sy, ey, 1./3.);
    float xx=x+cos(a)*l;
    float yy=y+sin(a)*l;
    koch.add(new Koch(sx, sy, x, y));
    koch.add(new Koch(x, y, xx, yy));
    x=lerp(sx, ex, 2./3.);
    y=lerp(sy, ey, 2./3.);
    koch.add(new Koch(xx, yy, x, y));
    koch.add(new Koch(x, y, ex, ey));
    return koch;
  }
}

実行結果

20150301000826.png
↑クリック6回したときの雪の結晶

参考文献

つらねの日記:http://turanegaku.hateblo.jp/entry/2015/03/01/002827

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1