Creative Coding · Session c03

Variables & Motion

How to make things move — smoothly and naturally.

A variable is a named box that holds a number. In p5.js, let size = 80 creates a variable called size that starts at 80. Because draw() runs 60 times per second, we can change that number on every frame — and the sketch will animate.

The secret ingredient for smooth, natural motion is sin(). The sine function goes back and forth between −1 and +1 endlessly, like a pendulum. Multiply it and add it to a base value and you get organic-looking breathing or pulsing.

frameCount is a variable p5.js keeps for you — it goes up by 1 every frame. So sin(frameCount * 0.05) gives you a slowly oscillating value between −1 and +1. Multiply it by 20 and add it to 80 and you get a number that smoothly drifts between 60 and 100 — a "breathing" size.

Live sketch — Breathing Jellyfish

function setup() { createCanvas(420, 260); } function draw() { background(10, 20, 60); // dark ocean // sin() smoothly oscillates between -1 and +1 let pulse = sin(frameCount * 0.05); // -1 to +1, slowly let size = 80 + pulse * 20; // 60 to 100 noStroke(); fill(180, 80, 220, 180); // purple, slightly transparent circle(width / 2, height / 2 - 20, size); // pulsing body stroke(180, 80, 220, 120); strokeWeight(2); for (let i = 0; i < 8; i++) { // draw 8 tentacles let angle = i * TWO_PI / 8; // evenly spaced around circle let wave = sin(frameCount * 0.05 + i) * 15; let tx = width/2 + cos(angle) * (size/2 + 28 + wave); let ty = height/2 - 20 + sin(angle) * (size/2 + 28 + wave); line(width/2, height/2 - 20, tx, ty); } }

The for loop

The loop for (let i = 0; i < 8; i++) runs the code inside the curly braces 8 times, with i taking the values 0, 1, 2, 3, 4, 5, 6, 7. This is how we draw 8 tentacles without writing the same line 8 times.

cos(angle) and sin(angle) give the x and y offsets on a circle — the same as in trigonometry! TWO_PI is 2π (≈ 6.28), a full circle in radians.

Challenges
  1. Change 0.05 to 0.1 (faster pulse) or 0.02 (slower). What feels most alive?
  2. Change the number of tentacles from 8 to 12, or to 3.
  3. Make the background slowly shift colour: replace background(10, 20, 60) with something that uses frameCount.
  4. Add a second jellyfish at a different x position and with a slight delay: start its pulse at frameCount * 0.05 + 1.5.
  5. Open challenge: Turn the jellyfish into a flower or a sun. What other shape can you make with sin() and a for loop?
Next session → c04: Mouse & Touch You'll build a finger-painting canvas that works on the iPad. Moving your finger draws a trail of colour that slowly cycles through the rainbow.
← All lessons
Focus 25:00

Ask your tutor