Pin Me

Adding Powerups

written by: Matthew Casperson•edited by: Michele McDonough•updated: 6/4/2010

At this point we have the basics of the players interaction with the level established. Now it's time to add some powerups.

  • slide 1 of 2


    The powerups in the game are represented by the Powerup class. This class is very simple, defining a value for the powerup and variables similar to those used by the Player class to follow a sine wave [code]. The Player class uses the sine wave to jump and fall, whereas the Powerup simply uses them to bounce up and down. [code]

    The Powerup also detects any collisions with the Player. There is a new function called collisionArea in the VisualGameObject [code] and AnimatedGameObject [code] classes that returns a Rectangle [code] class which defines the area on the screen that these objects takes up. In addition the Rectangle class contains a function called intersects [code] that can test if two rectangles are overlapping. The Powerup class uses the Rectangle returned by the Player and the one returned by it's own base AnimatedGameObject class to determine if the Player is colliding with the Powerup. If so the new gloabl variable g_score [code] is increased by the value of the Powerup. [code]


    The Level has been modified to include a new property called powerups [code], and a function called addPowerups [code]. The powerups property is a JavaScript object that is used as a dictionary, associating positions in the level (referring to the index in the blocks array) with a type of powerup [code]. In this case we have only one Powerup defined called Gem, but you could add more if needed.

    The ability to use an Object as a dictionary is a neat feature of JavaScript. Properties normally referred to by the dot notation (myObject.myProperty) can also be referenced by using square brackets, like an array, where the property is supplied as a string (myObject["myProperty"]). The addPowerups function uses this feature to loop through all the block stacks defined in the blocks array, check for any corresponding Powerup definitions in the powerups array, and then create a new Powerup object when a match has been found.


    The score itself is presented to the player through the HTML page rather than the Canvas element. This is because the canvas (or more specifically the CanvasRenderingContext2D) fillText and drawText functions are currently not well supported. In order to make the application compatible across the browsers that support the canvas element it was easier to simply add a DIV element to the HTML page [code], and have the ApplicationManager class update this value when the score is changed through a new function call updateScore. [code]

    Check out the demo here, download the source code here, and browse the source code documentation here.

    Read more in the Game Development with JavaScript and the Canvas element series.

  • slide 2 of 2