Home > Articles > Programming > Games

  • Print
  • + Share This
This chapter is from the book

Recipe: Adding Collectables

What does every platform adventurer love? That’s right—metal objects as big as they are, to collect and carry around while they try to run and jump.

Let’s start by editing the map again in Tiled. Add a new object layer (Layer... Add Object Layer) called coin. After adding the layer, add a new tileset for the coins (Map... New Tileset) and call the tileset coin as well. See Figure 5.5 to recall how to add objects to the screen.

For each coin added to the screen, be sure to right-click (Object Properties...) to set the name as coin, as well as the attributes image:coin and spritewidth:16. You can right-click to duplicate this object, and choose the selector tool to move it around. Note that it will create the clone directly above the original, so you may not initially realize that there are stacked objects until you move one.

Now we have quite a bit of code to add. Let’s start simply by adding coins to the entity pool in the loaded function of main.js, as in Listing 5.16, directly following where the PlayerEntity is added.

Listing 5.16. Adding Coins to the entityPool

me.entityPool.add("player", PlayerEntity);
me.entityPool.add("coin", CoinEntity);

Next, in Listing 5.17, add the coin file as an image resource within resources.js.

Listing 5.17. Adding the Coin Sprite to resources.js

}, // Reminder: Add these commas to preceding objects as you go!
{ name: "coin",
  type: "image",
  src: "coin.png"

Now, in Listing 5.18, create the CoinEntity at the end of the entities.js file.

Listing 5.18. Creating the CoinEntity

var CoinEntity = me.CollectableEntity.extend({
  init: function(x, y, settings) {
    this.parent(x, y, settings);
  onCollision : function (res, obj) {
    this.collidable = false;

Here, we start by declaring the CoinEntity as inheriting from CollectableEntity (which itself inherits from ObjectEntity). We then call the parent constructor to enable certain methods to be accessible. Last, we add some logic for collisions with the coin so that it cannot be collected twice.

Load index.html and notice how far we’ve come. Guy can now collect coins to pay for all his adventuring needs. Life might seem a little too good for Guy right now, though. Let’s add a little more conflict.

  • + Share This
  • 🔖 Save To Your Account