xxxxxxxxxx
44
function setup() {
createCanvas(400, 225);
noStroke();
}
function draw() {
// We'll feed this small frame by frame change into sin.
// Changing the divisor will speed up or slow down the transitions.
let tinyChange = frameCount / 100;
let dayBackground = color("skyBlue");
let nightBackground = color("black");
// Map the -1 to 1 swings of the changing sine output to the moon's
// verticle position on and off the screen.
let yPositionMoon = map(sin(tinyChange), -1, 1, 75, height * 3);
// Offset sin input by PI to place the sun and the moon on opposite "sides"
// of the wave. The moon peaks when the sun valleys, and vice versa.
let yPositionSun = map(sin(tinyChange + PI), -1, 1, 75, height * 4);
// Manually normalizing the sin wave between 0 and 1, instead of using map.
// Equivalent to: let lerpPosition = map(sin(tinyChange), -1, 1, 0, 1);
let lerpPosition = 0.5 * sin(tinyChange) + 0.5;
// Linear interpolation between the day and night sky.
let skyColor = lerpColor(nightBackground, dayBackground, lerpPosition);
// Sky
background(skyColor);
// Moon
fill("white");
circle(width / 4, yPositionMoon, 50);
// Sun
fill("yellow");
circle(width / 1.5, yPositionSun, 125);
// Grass
fill("green");
rect(0, height - 15, width, height);
}