Arrays & Objects
Store collections of data with arrays and objects.
Arrays
Arrays hold lists of values:
fn setup() {
size(300, 200)
}
fn draw() {
background(rgb(30, 30, 40))
let colors = [coral, cyan, yellow, purple, green]
for i in 0..len(colors) {
fill(colors[i])
circle(40 + i * 55, 100, 25)
}
}Adding to Arrays
Use push(array, value) to add items:
let particles = []
fn setup() {
size(300, 200)
}
fn draw() {
background(rgb(30, 30, 40))
// Add particle on click
if mousePressed {
push(particles, {
x: mouseX,
y: mouseY,
vx: random(-2, 2),
vy: random(-3, -1)
})
}
// Update and draw particles
for i in 0..len(particles) {
let p = particles[i]
p.x = p.x + p.vx
p.y = p.y + p.vy
p.vy = p.vy + 0.1
fill(coral)
circle(p.x, p.y, 8)
}
}Objects
Objects group related values together:
let ball = {
x: 150,
y: 100,
vx: 3,
vy: 2,
size: 20
}
fn setup() {
size(300, 200)
}
fn draw() {
background(rgb(30, 30, 40))
// Update position
ball.x = ball.x + ball.vx
ball.y = ball.y + ball.vy
// Bounce off walls
if ball.x < ball.size or ball.x > 300 - ball.size {
ball.vx = -ball.vx
}
if ball.y < ball.size or ball.y > 200 - ball.size {
ball.vy = -ball.vy
}
fill(coral)
circle(ball.x, ball.y, ball.size)
}Array Functions
len(array)- Number of itemspush(array, item)- Add item to endpop(array)- Remove and return last itemarray[i]- Get item at index i
Looping Over Arrays
Use for item in array to loop through items:
fn setup() {
size(300, 200)
}
fn draw() {
background(rgb(30, 30, 40))
let points = [
{x: 50, y: 50},
{x: 150, y: 30},
{x: 250, y: 80},
{x: 200, y: 150},
{x: 100, y: 170}
]
// Draw lines between points
stroke(coral)
strokeWeight(2)
for i in 0..len(points) - 1 {
let p1 = points[i]
let p2 = points[i + 1]
line(p1.x, p1.y, p2.x, p2.y)
}
// Draw points
noStroke()
fill(white)
for p in points {
circle(p.x, p.y, 8)
}
}