Functions
Create reusable blocks of code with functions.
Creating Functions
Use fn to define a function:
fn setup() {
size(300, 200)
}
fn draw() {
background(rgb(30, 30, 40))
// Call our custom function
drawFlower(100, 100)
drawFlower(200, 100)
}
fn drawFlower(x, y) {
fill(pink)
circle(x - 15, y, 15)
circle(x + 15, y, 15)
circle(x, y - 15, 15)
circle(x, y + 15, 15)
fill(yellow)
circle(x, y, 12)
}Parameters
Functions can take inputs (parameters) to customize behavior:
fn setup() {
size(300, 200)
}
fn draw() {
background(rgb(30, 30, 40))
// Same function, different sizes and colors
drawStar(75, 100, 30, coral)
drawStar(150, 100, 45, cyan)
drawStar(225, 100, 25, yellow)
}
fn drawStar(x, y, size, color) {
fill(color)
for i in 0..5 {
let angle = i * 72 - 90
let px = x + cos(radians(angle)) * size
let py = y + sin(radians(angle)) * size
circle(px, py, size / 3)
}
}Return Values
Functions can return a value with return:
fn setup() {
size(300, 200)
}
fn draw() {
background(rgb(30, 30, 40))
let d = distance(50, 50, mouseX, mouseY)
let size = map(d, 0, 300, 80, 10)
fill(coral)
circle(50, 50, size)
fill(white)
text("Distance: " + round(d), 20, 180)
}
fn distance(x1, y1, x2, y2) {
let dx = x2 - x1
let dy = y2 - y1
return sqrt(dx * dx + dy * dy)
}Built-in Math Functions
Bloom includes many useful functions:
sin(angle),cos(angle)- Trigonometry (radians)abs(n)- Absolute valueround(n)- Round to nearest integerfloor(n),ceil(n)- Round down/upmin(a, b),max(a, b)- Smaller/larger valuesqrt(n)- Square rootrandom(min, max)- Random numbermap(v, a, b, c, d)- Map value from one range to anotherlerp(a, b, t)- Linear interpolation