4:1 Randomness
We've already mentioned the random function briefly, but there's more to random than this. There are also different kinds of randomness.
random()
The random function in p5.js:
https://p5js.org/reference/#/p5/random
Random is a function that can either take no input, one input, two inputs or an array (we'll get onto arrays later). Its so unbelievably useful that we'll explore a little.
Look at how it can be used:
Using random for colour
Lets use random in an animation. By putting random in the draw loop it will choose a different value on every frame (60fps).
Firstly lets make random colours. So for a RGB colour we need to input a random number between 0 and 255 for RGB to get every possible colour.
Random position
Lets say we want to position randomly around the canvas we can input the system variables width and height into the random function.
Because this updates 60 times a second its going to look pretty crazy!
Using loops to make many random things
Why not make loads of circles and put them in random places, with random colours and random sizes. We will combine a loop with random();
for (let i = 0; i < 1000; i++) {
fill(random(255), random(255), random(255));
circle(random(width), random(height), random(50));
}
In the above code we make 1000 circles where everything is random. The system variables width and height are really useful here. The number between the brackets in the random function determines what kind of random number we get. For instance random(255) will give a number from 0 to 255, which is perfect for a RGB colour.
Controlling the colour
If you give random() 2 arguments they act as a min / max. This means we can have tighter control over what numbers we get.
Lets say we want our colours lighter and pinker.
fill(random(235, 255), random(150, 225), random(190, 255));
The code above makes red vary between 235 and 255, green varies between 150 and 225, blue varies between 190 and 255. The effect is still random, but with a more curated colour scheme.