Home / ๐Ÿ—“ Schedule / ๐Ÿ›  Examples / ๐Ÿ’ซ Guides / ๐Ÿ’Ž Resources

๐ŸŽ Variables {

โœจ Variables are the lifeblood of information in our program and, most important of all: they can change! And if they can change, then our program is alive! โœจ

Learning objectives

Template

Modules

Vimeo playlist for Variables

(Inline links below are for YuJa)

Examples

๐Ÿ”ฅ Hot tip: random()

There arenโ€™t many things more fun than random numbers. p5 has a function we can call to get a random number any time we want, and itโ€™s called random(). Importantly this function returns (gives back) a number that we can use in our program.

With no arguments we get a random number between 0 and 1, or we can give it two arguments to get a random number between those numbers. Usually weโ€™ll then store the returned number in a variable or use it directly somewhere else in our program.

A random greyscale fill:

let randomFill = random(0, 255);
fill(randomFill);

A random colour fill:

let r = random(0, 255);
let g = random(0, 255);
let b = random(0, 255);
fill(r, g, b);

A random position:

let x = random(0, width); // x is anywhere horizontally
let y = random(0, height); // y is anywhere vertically
ellipse(x, y, 100);

A bug (random movement):

let bug = {
    x: 0,
    y: 200,
    size: 10
};

function setup() {
    createCanvas(400, 400);
}

function draw() {
    background(0);
    // Add a random number between 1 and 5 to the big's position
    // to make it move jerkily
    bug.x += random(1, 5);
    ellipse(bug.x, bug.y, bug.size);
}

}