モノ創りで国造りを

ハード/ソフト問わず知見をまとめてます

Processingで再帰2

前回に続き、再帰の勉強。
f:id:yuji2yuji:20180826064558g:plain

rotateRectクラスのコンストラクタで、
その子供を生成します。
子供を生成が無限ループにならないよう、
生成する世代の上限を決めます。

    if (myGeneration < stopGeneration) {
      children = new Rect(angle, size, strokeMe, myGen + 1);
    }

画像を描画するupdateMe関数内に、
子供の画像描画を記述します。
ここでも無限ループに陥らないように条件分で世代の上限を記述しておきます。

if (myGeneration < stopGeneration) {
        children.updateMe();
      }

再帰の概念になれると、この程度はお茶の子さいさいです。

以下、ソース一覧。

Rect motherRect;

void setup() {
  size(1200, 1200);
  noStroke();
  background(255);
  smooth();
  frameRate(30);
  motherRect = new Rect(0, 900, 255, 0);
}

void draw() {
  background(255, 10);
  motherRect.updateMe();
}


class Rect {
  final float posX = width/2;
  final float posY = height/2;
  final float colorVar = 150;
  final float colorBase = 100;
  final float colorR = random(colorVar) + colorBase;
  final float colorG = random(colorVar) + colorBase;
  final float colorB = random(colorVar) + colorBase;
  final color colorMe = color(colorR, colorG, colorB, 200);
  float rotSpeed =0.1;

  float angle;
  float size;
  float centerX, centerY;
  float strokeMe;
  int myGeneration;

  int cnt=0;
  int emergeNextCnt = 10;
  int stopGeneration = 30;

  Rect children;


  Rect(float Angle, float Size, float StrokeMe, int myGen) {
    angle = Angle + radians(30);
    size = Size * 0.9;
    centerX = posX - size/2;
    centerY = posY - size/2;
    strokeMe = StrokeMe;
    myGeneration = myGen;
    rotSpeed = 1+myGeneration/2;

    if (myGeneration < stopGeneration) {
      children = new Rect(angle, size, strokeMe, myGen + 1);
    }
  }

  void updateMe() {
    fill(colorMe);
    stroke(strokeMe);
    pushMatrix();
    translate(width/2, height/2);
    rotate(angle + cnt*radians(rotSpeed));
    translate(-width/2, -height/2);
    rect(centerX, centerY, size, size);
    popMatrix();
    if (myGeneration < stopGeneration) {
      children.updateMe();
    }

    cnt++;
  }
}