Scripting Basics: pulling random values from within a defined range in After Effects

A common scripting requirement is to pull random values from within a defined range. For example, in the block dissolve transition the individual blocks of video are extracted from the video in a random order. Let’s revisit our float away video wall script and customize it to work in the same manner as a block dissolve but with a little more flair. We will scale the individual blocks up instead of just transitioning on and off.

The key to getting random values within a defined range is to first gather our values of interest in one container and then extract them randomly from the container and delete the item after it is selected. In our block dissolve, we will scale the individual grid items based on a simple timeline keyframe, so our container can simply be an increment counter of the number of values in the grid. Like so,

var gridArray = new Array();
var counter = 0;

for(x = 0; x < gridWidth; x++){
      for(y= 0; y < gridHeight; y++){

Later, when we need to randomize our values, we extract the numbers from the grid.

var random = Math.floor(Math.random() * gridArray.length);
var startTime = gridArray.splice(random, 1) *  (win.speed.value * .10);
var endTime  = startTime +  (win.speed.value * .10);
scaleProp.setValueAtTime(startTime, [0,0]);
scaleProp.setValueAtTime(endTime, [100,100]);

The splice Array method lets us extract the value from the array. The next time through we make the random values based on the length of the array, so that each time through the loop we are only pulling values for the remaining elements.

When I run the script, I get results like this

Because of the overhead of creating layers, this technique is especially useful in creating Gradient Wipes or Beauty/Matte passes. For example if we replace the above code with something like...

var startTime = (x + y) *  (win.speed.value * .10);
var endTime = startTime +  (win.speed.value * .10);
scaleProp.setValueAtTime(startTime, [0,0]);
scaleProp.setValueAtTime(endTime, [100,100]);

We then get this.

We can introduce some trig functions for some springy transitions, spirals etc. There are a lot of possibilities. Feel free to share some of your ideas and I'll put them up here.

Source JSX script

Comments are closed.