Animating the drawing of trees / "growing" trees

Hello all,

I've got a simple tree function to generate trees recursively to a page and have them slowly fade out. Currently the entire tree generates all at once, but I'd ideally like to animate the tree growth by having the recursive calls to the branch function happen on a later frame of my draw(). Anyone have any ideas on what I need to do? I tried using delay(100) but that definitely did not work.

Here is my code:

var sketchWidth = 1000;
var sketchHeight = 500;
var currentTime = millis();
var sliderTimer, sliderBranchAngle;


function setup(){
  var myCanvas = createCanvas(sketchWidth, sketchHeight);
  myCanvas.parent('invisibleCitiesSketch');
  sliderTimer = createSlider(1, 48, 25);
  sliderBranchAngle = createSlider(10, 100, 55);


  background(0);
  frameRate(24);
  smooth();
  fill(0,12);
}

function draw(){
   noStroke();
   fill(0,15);
   rect(0,0,width,height);
   if(frameCount % sliderTimer.value() == 0){
    stroke(255);
    branch(random(50, 950), height, height-random(250, 450), radians(270));
   }
}

function branch(x, y, s, a){
  strokeWeight(s*.05);
  a+=radians(1.1*random(-10,10));
  var newx = x+cos(a)*s;
  var newy = y+sin(a)*s;
  line(x,y,newx,newy);
  if(s > 2){
    for(var i = 0; i < random(1,2); i++){
      branch(newx, newy, s*(random(0.15,0.75)), a+radians(random(0,sliderBranchAngle.value()))); //make this user changable
      branch(newx, newy, s*(random(0.15,0.75)), a-radians(random(0,sliderBranchAngle.value())));
    }
  }
}

function mousePressed(){
   stroke(255);
   branch(mouseX, height, height-mouseY, radians(270));
}
Tagged:

Answers

Sign In or Register to comment.