Chapter 6, Exercise 2 – Popping Orphaned Bubbles

When orphaned bubbles fall, they remain as the default sprite. Change renderer.js so that bubbles pop as they’re falling.

To do this we can tap into our state machine and change the image that’s rendered as the bubble falls. We’ll add a delay, so that bubbles start to fall and then pop after 500 milliseconds. Make the following change to the render function in renderer.js:

render : function(bubbles){
  context.clearRect(0,0,canvas.width,canvas.height);
  context.translate(120,0);
  $.each(bubbles,function(){
    var bubble = this;
    var clip = {
      top : bubble.getType() * BUBBLE_IMAGE_DIM,
      left : 0
    };
      switch(bubble.getState()){
        case BubbleShoot.BubbleState.POPPING:
          var timeInState = bubble.getTimeInState();
          if(timeInState < 80){
            clip.left = BUBBLE_IMAGE_DIM;
            }else if(timeInState < 140){
            clip.left = BUBBLE_IMAGE_DIM*2;
            }else{
            clip.left = BUBBLE_IMAGE_DIM*3;
          };
          break;
        case BubbleShoot.BubbleState.POPPED:
          return;
        case BubbleShoot.BubbleState.FIRED:
          return;
        case BubbleShoot.BubbleState.FALLING:
          var timeInState = bubble.getTimeInState();
          if(timeInState < 500){
            clip.left = 0;
          }else if(timeInState < 600){
            clip.left = BUBBLE_IMAGE_DIM;
          }else if(timeInState < 700){
            clip.left = BUBBLE_IMAGE_DIM*2;
          }else if(timeInState < 800){
            clip.left = BUBBLE_IMAGE_DIM*3;
          }else{
            return;
          }
          break;
        case BubbleShoot.BubbleState.FALLEN:
          return;
      }
    Renderer.drawSprite(bubble.getSprite(),clip);
  });
  context.translate(-120,0);
}

It would be nicer to have a different animation, but this illustrates the moving a sprite on the canvas and animating it frame-by-frame at the same time is no more complicated than either operation alone.

Leave a Reply

Your email address will not be published. Required fields are marked *