Search code examples
javascriptcode.org

Conditionals issue in JS with the visible block


I can't fix my problem on this task. Here it is:

Do This: Make the balloon pop when it hits the edge of the game area!

Add a conditional that checks to see whether the balloon has hit the edge. Use a watcher on balloon.scale to help you out. Create a pop sprite which uses the "pop" visual in the animation tab. Use the visible property to keep the "pop" sprite hidden at the beginning. Inside the if add two statements. One that sets the visible property to hide the balloon sprite. One that sets the visible property to show the pop sprite.

I tried some combinations with the visible block, but my tries were useless. I still don't know the full potential of this block. I tried debugging it with console.log();, but it didn't work either.

Here is the original code:

var balloon = createSprite(200, 200);
balloon.setAnimation("balloon");
balloon.scale = 0.1;

function draw() {
  // Draw Background
  background("white");
  
  // Update Values
  balloon.scale = balloon.scale + 0.001;

  // Draw Animations
  drawSprites();
}

This is my code:

var balloon = createSprite(200, 200);
balloon.setAnimation("balloon");
balloon.scale = 0.1;
var pop = createSprite(200,200);
pop.visible = false;

function draw() {
  // Draw Background
  background("white");
  
  // Update Values
  balloon.scale = balloon.scale + 0.002;
  if (balloon.scale == 0.6){
    pop.visible = true;
    balloon.visible = false; 
    pop.setAnimation("pop");
  }

  // Draw Animations
  drawSprites();
}

Here is a link to the site I learn coding: https://studio.code.org/s/csd3-virtual/lessons/10/levels/10/sublevel/1/

Thanks a lot and have a nice weekend!


Solution

  • Fix Balloon Pop Condition

    Your code is close to correct, but has one small problem that prevents the balloon from popping like you expect.

    The code expands the balloon and pops it when: (balloon.scale == 0.6)

    Yet, this condition is only true for one frame. The balloon pops quickly and then goes back to expanding again. You can fix this problem by changing the condition to (ballon.scale > 0.6). This works because now the condition toggles to true once the balloon expands beyond the limit.

    Here is the modified code, which can also be viewed in the Code.org IDE here.

    var balloon = createSprite(200, 200);
    balloon.setAnimation("balloon");
    balloon.scale = 0.1;
    var pop = createSprite(200,200);
    pop.setAnimation("pop");
    pop.visible = false;
    
    function draw() {
      background("white");
      if (balloon.scale < 1) {
        balloon.scale = balloon.scale + 0.05;
      } else {
        balloon.visible = false;
        pop.visible = true;
      }
      drawSprites();
    }