setup()
setup() runs exactly once when the sketch starts. It's the right place to build data structures (like the stars array) that don't need to be rebuilt every frame - only their drawn appearance changes in draw().
🔬 This loop fills the stars array once at startup. What happens visually if you change random(1, 3) to random(1, 8) so stars vary a lot more in size?
for (let i = 0; i < 200; i++) { stars.push({ x: random(width), y: random(height), size: random(1, 3), alphaOffset: random(TWO_PI) }); }
function setup() {
createCanvas(windowWidth, windowHeight);
for (let i = 0; i < 200; i++) { stars.push({ x: random(width), y: random(height), size: random(1, 3), alphaOffset: random(TWO_PI) }); }
moonX = width / 2;
moonY = height / 2;
}
Line-by-line explanation (4 lines)
🔧 Subcomponents:
for (let i = 0; i < 200; i++) { stars.push({ x: random(width), y: random(height), size: random(1, 3), alphaOffset: random(TWO_PI) }); }
Creates 200 star objects with random positions, sizes, and a random phase offset used for twinkling, and stores them in the stars array.
createCanvas(windowWidth, windowHeight);- Creates a canvas that fills the entire browser window, so the sky and moon scale to any screen size.
for (let i = 0; i < 200; i++) { stars.push({ x: random(width), y: random(height), size: random(1, 3), alphaOffset: random(TWO_PI) }); }- Runs 200 times, each time pushing a new star object into the stars array with a random x/y position, a random size between 1 and 3 pixels, and a random alphaOffset (a starting point in a sine wave) so not all stars twinkle in sync.
moonX = width / 2;- Positions the moon horizontally at the center of the canvas.
moonY = height / 2;- Positions the moon vertically at the center of the canvas.