2018년 4월 10일 화요일

[프로세싱] 재귀 함수 예제 - 벚꽃 그리기

아래의 그림은 프로세싱의 재귀함수를 이용해서 벚꽃을 그린 것이다.
재귀함수를 사용하면 코드를 보다 간결하게 표현할 수 있고, 반복되는 코드를 줄여서 재귀함수의 구조를 이해한다면 간결하게 표현할 수 있다.



아래의 사진과 코드를 살펴보자.




 void setup(){

  size(600,600,P3D);  smooth();  noLoop();}
void draw(){  background(255);  strokeWeight(10);
  for(int i=-300; i<=300; i+=80){
//pushMatrix(); 와 popMatrix 사이에서 선언되는 translate() 와 같은 값변경은, 둘 사이세서만 적용이 되고, 둘 사이가 아닌 코드에는 영향을 끼치지않는다.
    pushMatrix();
    translate(width/2+i, height-20,i);
    branch(0);
    popMatrix();
  }
}
void branch(int depth){
  if(depth<12){
    line(0,0,0,-height/10);
    {
      translate(0,-height/10);
      rotate(random(-0.1,0.1));
 
    if(random(1.0)<0.6){
      rotate(0.3);
      scale(0.7);
      pushMatrix();
      branch(depth +1);
      popMatrix();
      rotate(-0.6);
      pushMatrix();
      branch(depth +1);
      popMatrix();
    }
    else{
      branch(depth);
    }
  }
}
  else {
    noStroke();
    fill(#FFBFF9,150);
    ellipse(0,0,random(100,300),random(100,300));
    stroke(0);
  }
 }

 //마우스 버튼을 클릭하면 다시 그린다.
 void mouseReleased(){
   redraw();
 }

댓글 없음:

댓글 쓰기