I'm rather new to programming, and as a mini project to help me get better with JavaScript, I'm making a sun set. The background starts blue, and at a certain point, the background has to turn black, and I did most of this, I just don't know how to make it permenantly black.
noStroke();
// Original y position of the sun
var sunPosition = 50;
function draw() {
// Draw sky
background("skyblue");
// Move the sun down
sunPosition = sunPosition + 1;
if(sunPosition === 348){
background("black");
}
// Draw sun
fill("yellow");
ellipse(350,sunPosition,50,50);
// Draw grass
fill("green");
rect(0,300,400,100);
}
You could try changing this line:
if(sunPosition === 348){
to this:
if(sunPosition >= 348){
to get the desired result.
This sounds like a great way to learn. Kudos.
I assume the code that you have posted is running within a loop of some kind. Each iteration of the loop increments the sunPosition
.
However you're only checking that sunPosition
is exactly equal to 348
.
Instead, check whether it's greater than or equal to 348
.
if(sunPosition >= 348){
background("black");
}
Or, you can stop the loop here somehow.
if(sunPosition === 348){
background("black");
stopLoopSomehow();
}
You can make a mutable variable, like your sunPosition
, to store whether the sun has already set:
// Original y position of the sun
var sunPosition = 50;
// Original color of sky
var skyColor = "skyblue";
function draw() {
// Move the sun down
sunPosition = sunPosition + 1;
// check for sunset
if (sunPosition === 348) {
skyColor = "black";
}
// Draw sky
background(skyColor);
// Draw sun
fill("yellow");
ellipse(350,sunPosition,50,50);
// Draw grass
fill("green");
rect(0,300,400,100);
}
Alternatively (and more robust, as you don't need to exactly hit the change condition), is to compute the sky color on every draw
call, depending on the sun position:
function draw() {
// Move the sun down
sunPosition = sunPosition + 1;
// Draw sky
if (sunPosition >= 348) {
background("skyblue");
} else {
background("black");
}
// Draw sun
fill("yellow");
ellipse(350,sunPosition,50,50);
// Draw grass
fill("green");
rect(0,300,400,100);
}
With the if
/else
, it'll become clear why you want to use >=
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With