← All lessons/Capstone Projects· Lesson 31 of 32

Starfield

Build an array of star objects in a loop, then draw the whole field every frame — arrays, objects, loops, and functions working together.

About 14 min

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);
One star, described as an object.

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 the array once, with a loop.

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:

A full starfield — an array of objects, drawn in a loop.

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.

Your turn

Make your own starfield. Build an array of at least 50 star objects with a for loop (each an object with x, y, and size from random(...)), then write a function drawStars() that loops over the array and draws each one with ellipse. Call drawStars() from draw().

  • Start with let stars = []; then a for loop that runs 50+ times.
  • Each pass, stars.push({ x: random(0, 400), y: random(0, 400), size: random(1, 4) });.
  • Define function drawStars() that loops over stars and draws an ellipse for each.
  • In draw(), clear the background and call drawStars().
Hints