Star class
The Star class demonstrates two key ideas: storing per-object randomized data (like twinkleOffset) in the constructor, and using trigonometric functions (sine) to create smooth, cyclical animations. Every star gets a unique phase offset so they twinkle at different times, which feels more natural than all stars pulsing in unison.
class Star {
constructor() {
this.x = random(width);
this.y = random(height / 2);
this.size = random(1, 3);
this.twinkleOffset = random(TWO_PI);
}
show(alpha) {
// Only show if alpha is greater than 0
if (alpha <= 0) return;
// Calculate twinkling effect
let twinkleAlpha = map(sin(frameCount * 0.1 + this.twinkleOffset), -1, 1, 0.5, 1);
fill(255, alpha * twinkleAlpha);
circle(this.x, this.y, this.size);
}
}
Line-by-line explanation (8 lines)
🔧 Subcomponents:
this.twinkleOffset = random(TWO_PI);
Gives each star a unique phase offset so they don't all twinkle in sync
let twinkleAlpha = map(sin(frameCount * 0.1 + this.twinkleOffset), -1, 1, 0.5, 1);
Uses sine wave to smoothly vary opacity, creating a realistic twinkle
this.x = random(width);- Places each star at a random horizontal position across the full canvas width
this.y = random(height / 2);- Places each star in the upper half of the sky only, not in the lower ground area
this.size = random(1, 3);- Each star is a tiny circle between 1 and 3 pixels wide for a natural look
this.twinkleOffset = random(TWO_PI);- Stores a random angle (0 to 2π) that shifts the sine wave timing for this star alone
if (alpha <= 0) return;- Skips drawing if the alpha is zero or negative—a performance optimization that avoids invisible pixels
let twinkleAlpha = map(sin(frameCount * 0.1 + this.twinkleOffset), -1, 1, 0.5, 1);- The sine function oscillates between -1 and 1 over time; map() converts it to 0.5–1.0 opacity so stars fade in and out smoothly
fill(255, alpha * twinkleAlpha);- Multiplies the incoming alpha (from the draw function) by the twinkle alpha to fade the entire star group out while keeping individual twinkles
circle(this.x, this.y, this.size);- Draws a white circle at the star's position with its size