Animation
Make things move by using the frame counter and variables.
The Frame Counter
The built-in frame variable counts up every time draw() runs:
- Frame 0, 1, 2, 3... (increases by 1 each frame)
- At 60 frames per second, frame 60 = 1 second
fn setup() {
size(400, 200)
}
fn draw() {
background(rgb(20, 20, 30))
// Move circle using frame
fill(coral)
circle(frame % 400, 100, 30)
fill(white)
text("Frame: " + frame, 10, 30)
}The % operator (modulo) wraps the value around. When frame reaches 400, it resets to 0.
Smooth Motion with sin()
Use sin() for smooth back-and-forth motion. It returns values between -1 and 1.
fn setup() {
size(400, 200)
}
fn draw() {
background(rgb(20, 20, 30))
// Smooth oscillation
let x = 200 + sin(frame * 0.05) * 100
let size = 30 + sin(frame * 0.1) * 10
fill(cyan)
circle(x, 100, size)
}Using Variables for State
Variables defined outside functions keep their values between frames:
let x = 50
let speed = 3
fn setup() {
size(400, 200)
}
fn draw() {
background(rgb(20, 20, 30))
// Move x by speed each frame
x = x + speed
// Bounce off edges
if x > 370 or x < 30 {
speed = -speed
}
fill(pink)
circle(x, 100, 30)
}Animation Patterns
Circular Motion
fn setup() {
size(300, 300)
}
fn draw() {
background(rgb(20, 20, 30))
let angle = frame * 0.03
let x = 150 + cos(angle) * 80
let y = 150 + sin(angle) * 80
fill(coral)
circle(x, y, 25)
}Multiple Objects
fn setup() {
size(400, 200)
}
fn draw() {
background(rgb(15, 15, 25))
for i in 0..5 {
let x = 50 + i * 80
let y = 100 + sin(frame * 0.05 + i) * 40
let hue = (i * 60 + frame) % 360
fill(hsl(hue, 70, 60))
circle(x, y, 25)
}
}Trails Effect
Use a semi-transparent background for motion trails:
fn setup() {
size(400, 200)
}
fn draw() {
// Semi-transparent to create trails
fill(rgba(20, 20, 30, 0.1))
rect(0, 0, 400, 200)
let x = 200 + cos(frame * 0.03) * 150
let y = 100 + sin(frame * 0.05) * 60
fill(cyan)
circle(x, y, 15)
}