Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make an if-statement permanent?

Tags:

javascript

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);
   }
like image 234
retnuH Avatar asked Feb 07 '19 16:02

retnuH


3 Answers

You could try changing this line: if(sunPosition === 348){

to this: if(sunPosition >= 348){

to get the desired result.

like image 113
Grillparzer Avatar answered Oct 30 '22 23:10

Grillparzer


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();
}
like image 20
Raphael Rafatpanah Avatar answered Oct 30 '22 22:10

Raphael Rafatpanah


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 >=.

like image 30
Bergi Avatar answered Oct 30 '22 23:10

Bergi