Skip to main content

Random & Noise

Learn how to create randomness, variation, and organic patterns in your games.

Basic Random Numbers

Generate random numbers with random():

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

function draw() {
background(220);

// Random number between 0 and 400
let x = random(400);
let y = random(400);

// Draw circle at random position
circle(x, y, 20);
}

Breaking it down

  • random(max) - Returns random number from 0 to max (not including max)
  • random(min, max) - Returns random number between min and max
  • Different every time you call it
  • Returns decimal numbers (floats)

Random Range

Get random numbers in a specific range:

// Random between 0 and 100
let score = random(100);

// Random between 50 and 150
let speed = random(50, 150);

// Random between -10 and 10
let offset = random(-10, 10);

Breaking it down

  • One parameter: 0 to that number
  • Two parameters: between first and second number
  • Can use negative numbers
  • Always returns a decimal value

Random Integers (Whole Numbers)

Get random whole numbers:

function draw() {
background(220);

// Random integer from 1 to 6 (like a dice)
let dice = floor(random(1, 7));

textSize(48);
textAlign(CENTER, CENTER);
text(dice, 200, 200);
}

function mousePressed() {
// Re-roll
redraw();
}

Breaking it down

  • floor() - Rounds down to nearest whole number
  • random(1, 7) gives 1.0 to 6.999...
  • floor() converts to 1, 2, 3, 4, 5, or 6
  • Use for: dice rolls, card draws, random choices

Random Choice from Array

Pick a random item from a list:

let colors = ['red', 'blue', 'green', 'yellow', 'purple'];
let fruits = ['🍎', '🍌', '🍊', '🍇', '🍓'];

function draw() {
background(220);

// Pick random color
let randomColor = random(colors);
fill(randomColor);
circle(150, 200, 100);

// Pick random fruit emoji
let randomFruit = random(fruits);
textSize(64);
text(randomFruit, 280, 200);
}

function mousePressed() {
redraw();
}

Breaking it down

  • random(array) - Returns random element from array
  • Works with any array (strings, numbers, objects)
  • Each element has equal chance of being picked
  • Original array is not modified

Random Colors

Generate random RGB colors:

function draw() {
// Random color for background
let r = random(255);
let g = random(255);
let b = random(255);
background(r, g, b);

// Random color for circle
fill(random(255), random(255), random(255));
circle(200, 200, 100);
}

function mousePressed() {
redraw();
}

Breaking it down

  • Each color channel (R, G, B) can be random
  • random(255) gives any value from 0 to 255
  • Creates unpredictable color combinations
  • Call once per object to keep color consistent per frame

Controlled Randomness (Random Seed)

Make "random" numbers repeatable:

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

// Same seed = same "random" sequence
randomSeed(42);

// These will be the same every time you run
for (let i = 0; i < 10; i++) {
let x = random(width);
let y = random(height);
circle(x, y, 20);
}

noLoop();
}

Breaking it down

  • randomSeed(number) - Sets the starting point for random sequence
  • Same seed always produces same random numbers
  • Useful for: testing, procedural generation, replay systems
  • Different seed = different sequence

Random Chance (Probability)

Make things happen with a certain probability:

function draw() {
background(220);

// 30% chance of spawning an enemy each frame
if (random() < 0.3) {
spawnEnemy();
}

// 50% chance (coin flip)
if (random() < 0.5) {
// Heads
} else {
// Tails
}
}

Breaking it down

  • random() with no parameters returns 0 to 1
  • Compare to probability (0.3 = 30% chance)
  • 0 = never happens, 1 = always happens
  • Use for: random events, drops, spawning

Perlin Noise

Create smooth, organic randomness:

let xOffset = 0;

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

function draw() {
background(220);

// Get smooth noise value (0 to 1)
let n = noise(xOffset);

// Map to y position
let y = map(n, 0, 1, 0, height);

circle(200, y, 50);

// Move along noise space
xOffset += 0.01;
}

Breaking it down

  • noise(x) - Returns smooth value from 0 to 1
  • Nearby inputs give nearby outputs (smooth transitions)
  • Creates natural-looking movement
  • Much smoother than random()

2D Noise (Terrain/Clouds)

Use noise for textures and patterns:

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

function draw() {
background(220);

// Create cloud-like pattern
for (let x = 0; x < width; x += 5) {
for (let y = 0; y < height; y += 5) {
// Get noise value based on position
let n = noise(x * 0.01, y * 0.01);

// Map to grayscale color
let brightness = map(n, 0, 1, 0, 255);
fill(brightness);
noStroke();
rect(x, y, 5, 5);
}
}
}

Breaking it down

  • noise(x, y) - 2D noise based on two coordinates
  • Multiply coordinates by small number (0.01) for larger patterns
  • Creates organic, cloud-like patterns
  • Good for: terrain, textures, backgrounds

Animated Noise

Make things move organically:

let particles = [];
let time = 0;

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

// Create particles
for (let i = 0; i < 50; i++) {
particles.push({
x: random(width),
y: random(height),
offsetX: random(1000),
offsetY: random(5000)
});
}
}

function draw() {
background(220, 220, 220, 25); // Trails

for (let p of particles) {
// Use noise for smooth movement
let nx = noise(p.offsetX + time);
let ny = noise(p.offsetY + time);

p.x = map(nx, 0, 1, 0, width);
p.y = map(ny, 0, 1, 0, height);

fill(100, 150, 250);
noStroke();
circle(p.x, p.y, 8);
}

time += 0.01;
}

Breaking it down

  • Give each particle unique noise offsets
  • Increment time each frame to animate
  • map() converts noise (0-1) to screen coordinates
  • Creates flowing, organic motion

Common Patterns

Random Spawning

let enemies = [];

function draw() {
background(220);

// 2% chance each frame to spawn enemy
if (random() < 0.02) {
enemies.push({
x: random(width),
y: 0,
speed: random(2, 5)
});
}

// Update and draw enemies
for (let e of enemies) {
e.y += e.speed;
circle(e.x, e.y, 30);
}
}

Random Power-ups

function spawnPowerUp() {
let types = ['health', 'speed', 'shield'];
let type = random(types);

return {
x: random(50, width - 50),
y: random(50, height - 50),
type: type
};
}

Shake Effect

let shakeAmount = 0;

function draw() {
// Apply shake to everything
translate(random(-shakeAmount, shakeAmount),
random(-shakeAmount, shakeAmount));

background(220);

// Reduce shake over time
shakeAmount *= 0.9;

// Draw game
circle(200, 200, 50);
}

function mousePressed() {
// Trigger shake
shakeAmount = 10;
}

Procedural Star Field

function setup() {
createCanvas(400, 400);
background(0);

randomSeed(99); // Same stars every time

// Generate 200 stars
for (let i = 0; i < 200; i++) {
let x = random(width);
let y = random(height);
let size = random(1, 4);
let brightness = random(150, 255);

fill(brightness);
noStroke();
circle(x, y, size);
}

noLoop();
}

Random vs Noise

Featurerandom()noise()
OutputCompletely randomSmooth, continuous
PredictableNo (unless seeded)Yes (deterministic)
Use forSudden events, choicesMovement, terrain, organic patterns
SpeedVery fastSlightly slower
VisualChaotic, jumpySmooth, natural

Tips & Tricks

  1. floor() for integers - Use with random for whole numbers
  2. Seed for testing - Use randomSeed() to reproduce bugs
  3. Noise scale - Multiply coordinates by small values (0.01) for bigger patterns
  4. Unique offsets - Give each object different noise offset for variety
  5. Map is your friend - Convert noise (0-1) to any range you need
  6. Probability checks - random() < 0.3 for 30% chance
  • random() - Random value
  • randomSeed() - Set random seed
  • noise() - Perlin noise value
  • noiseSeed() - Set noise seed
  • noiseDetail() - Control noise quality
  • floor() - Round down
  • ceil() - Round up
  • round() - Round to nearest
  • map() - Convert value from one range to another

Common Gotchas

⚠️ random(100) - Goes from 0 to 100, not 1 to 100
⚠️ noise returns 0-1 - Always need to map to your desired range
⚠️ noise is 3D - Can use noise(x, y, z) for time-based animation
⚠️ noise scale matters - Small changes = smooth, large changes = rough
⚠️ random isn't truly random - It's pseudorandom (good enough for games!)

Try It Yourself

Experiment with these ideas:

  • Create a dice rolling game
  • Make random power-ups spawn around the map
  • Generate a random terrain with noise
  • Add screen shake when the player is hit
  • Create particles that move with smooth noise
  • Make a random color palette generator

Great job learning all the common p5.js elements! Now you can combine these techniques to create amazing games. Check out the Cookie Clicker or Worm tutorials to see everything in action! 🎮