1

I'm coding a tree in different seasons (though the original code for the trunk and randomized branches is not my own). For winter, I want to keep the tree randomized, but also have animated snowflakes.

However, each time the function that makes the tree is called, the random numbers are (obviously) different. It there a way to save the output of the function (or just of the random() functions within it) and just draw that output?

The draw() function calls the function that makes the tree, so if it is called multiple times, the tree will rapidly change, since it is randomized each time. The tree function has to repeat itself to draw the tree, so there are a lot of random numbers. Ultimately, I just want to draw a randomized tree, and then repeatedly draw that same tree, so that the draw function can repeatedly run and not cover up the tree. Here are the 2 lines of code with the random numbers I want to save:

rotate(random(-0.05,0.05));
    if (random(1.0) < 0.6) {
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
Ian Rispin
  • 11
  • 1

2 Answers2

1

You want to use the randomSeed() function here. If you call it at the top of your draw() function each time, with the same number, then you will get the same 'random' tree. If you change the number, you will get a different 'random' tree. If you want a new tree (perhaps when the mouse is clicked), then you can change the number. For example:

let rs;

function setup() {
  rs = random(0, 1000);

  // your code
}

function draw() {
  randomSeed(rs);

  // your code
}

function mouseClicked {
  rs = random(0, 1000);
}
rednoyz
  • 1,318
  • 10
  • 24
0

You could do this by storing the values in variables. Here's a simplified example:

var x;
var y;

function setup(){
  createCanvas(500, 500);
  x = random(width);
  y = random(height);
}

function draw(){
  background(32);
  ellipse(x, y, 25, 25);
}

This is just a simple example, but you could get fancier by using something like a Tree class that stores its own values. But the idea is the same: generate the random value once, store it in a variable, and then use that variable when you draw it.

You could also draw the tree to a buffer once, and then draw that buffer to the screen. The createGraphics() function would come in handy for this approach.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107