Random values
Note: These docs were adopted from the original Motion Canvas docs
Randomly generated values can be used to create a sense of variety and
unpredictability in your animation. In Motion Canvas, it's achieved using the
useRandom()
function. It returns a random number
generator (RNG) for the current scene:
import {useRandom} from '@revideo/core';
const random = useRandom();
const integer = random.nextInt(0, 10);
In this case, calling nextInt()
will return an integer in the range from 0 to
10 (exclusive). Check the Random
api to see all
available methods.
Unlike Math.random()
, useRandom()
is completely reproducible - each time the
animation is played the generated values will be exactly the same. The seed used
to generate these numbers is stored in the meta file of each scene.
You can also provide your own seed to find a sequence of numbers that best suits your needs:
const random = useRandom(123);
The animation at the top of this page uses a random number generator to vary the height of rectangles and make them look like a sound-wave:
import {Layout, Rect, makeScene2D} from '@revideo/2d';
import {all, loop, makeRef, range, sequence, useRandom} from '@revideo/core';
export default makeScene2D(function* (view) {
const random = useRandom();
const rects: Rect[] = [];
view.add(
<Layout layout gap={10} alignItems="center">
{range(40).map(i => (
<Rect
ref={makeRef(rects, i)}
radius={5}
width={10}
height={10}
fill={'#e13238'}
/>
))}
</Layout>,
);
yield* loop(3, () =>
sequence(
0.04,
...rects.map(rect =>
all(
rect.size.y(random.nextInt(100, 200), 0.5).to(10, 0.5),
rect.fill('#e6a700', 0.5).to('#e13238', 0.5),
),
),
),
);
});