Many things at once
A single bouncing ball is great, but real sketches manage lots of things — hundreds of stars, particles, or enemies. The pattern that makes this manageable brings together four ideas: store each thing as an object, keep all of them in an array, build that array with a loop, and draw it with another loop — often tidied up inside a function.
A star is an object
Each star needs to remember a few values: where it is and how big it is. An object bundles those together with named properties.
let star = { x: 100, y: 50, size: 3 };
// read a property with a dot:
ellipse(star.x, star.y, star.size, star.size);Many stars in an array
We don't want to type out 100 stars by hand. Start with an empty array, then use a loop to push a brand-new star object into it each pass. random(0, 400) gives a fresh random position for every one.
let stars = [];
for (let i = 0; i < 100; i++) {
stars.push({
x: random(0, 400),
y: random(0, 400),
size: random(1, 4),
});
}Build once, draw every frame
We create the stars at the top level so it happens a single time. Drawing them, on the other hand, goes inside draw() so the field is painted on every frame.
Drawing the field
To paint the sky, loop over the array and draw each star. Wrapping that loop in a helper function like drawStars() keeps draw() short and readable:
stars.length
Looping to stars.length instead of a fixed number means your loop automatically draws every star, no matter how many you created. Add more stars and the drawing code just works.