Skip to content

Random in animated examples#

Example 1#

void setup() {
  size(300, 300);
  noStroke();
  background(0, 0, 0);
}

void draw() {
  float x = random(0, 300);
  float y = random(0, 300);
  float alpha = random(0, 255);

  fill(255, 0, 0, alpha);
  circle(x, y, 5);
}

Each frame, we draw a single red circle. We're randomly choosing its position and alpha value. Eventually the whole canvas will be fully red.

Example 2#

float smoothedSize = 0;

void setup() {
  size(300, 300);
  noStroke();
}

void draw() {
  float redComponent = random(220, 255);
  float greenComponent = random(100, 150);
  float blueComponent = random(0, 50);

  float newSize = random(100, 250);
  smoothedSize = smoothedSize * 0.95 + newSize * 0.05;

  background(0, 0, 0);
  fill(redComponent, greenComponent, blueComponent);
  circle(150, 150, smoothedSize);
}

This code example creates a lot of random values for each freshly drawn frame. We use those in red, green and blue directly, so the colour can be quite flickery.

For the size of the circle, we do something different, though: We have one variable, that also changes every single frame (newSize), but that is not the size we are drawing at. For drawing, we use a variable that we called smoothedSize - and it will always be "mostly what it was the frame before" (95% come from its last known value) and then we add a tiny little bit of our new random value (5% come from newSize). This is also why the circle starts out tiny in the beginning. Over the first couple of frames it has to "inflate" to the more normal value we see later in the video.