Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning Cocos2d-JS Game Development

You're reading from   Learning Cocos2d-JS Game Development Learn to create robust and engaging cross-platform HTML5 games using Cocos2d-JS

Arrow left icon
Product type Paperback
Published in Jan 2015
Publisher
ISBN-13 9781784390075
Length 188 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Emanuele Feronato Emanuele Feronato
Author Profile Icon Emanuele Feronato
Emanuele Feronato
Arrow right icon
View More author details
Toc

Table of Contents (11) Chapters Close

Preface 1. Hello World – A Cross-platform Game FREE CHAPTER 2. Adding Interactivity – The Making of a Concentration Game 3. Moving Sprites Around the Screen – An Endless Runner 4. Learn about Swipes through the making of Sokoban 5. Become a Musical Maestro 6. Controlling the Game with Virtual Pads 7. Adding Physics to Your Games Using the Box2D Engine 8. Adding Physics to Your Games Using the Chipmunk2D Engine 9. Creating Your Own Blockbuster Game – A Complete Match 3 Game Index

Preloading and adding images

In this example, I am using a 64x64 PNG image representing a target, as shown in the following figure:

Preloading and adding images

You are obviously free to use whatever image you prefer.

When you load a web page, in most cases, the page is loaded and shown before all images are loaded. This might sound okay on a web page because readers won't mind if they have to wait a couple of seconds before an image is showed, but this definitively can't happen in a game. This means our images need to be preloaded, and Cocos2d-JS can easily handle this. The steps on how to preload images in your game are as follows:

  1. This is the first time you add this line to the project.json file:
    {
      "debugMode" : 0,
      "showFPS" : false,
      "frameRate" : 60,
      "id" : "gameCanvas",
      "renderMode" : 0,
      "engineDir":"cocos2d-html5/",
    
      "modules" : ["cocos2d"],
    
      "jsList" : [
        "src/loadassets.js",
        "src/gamescript.js"
      ]
    }

    This means you are going to create another file called loadassets.js in the same src folder where you just created gamescript.js.

    This is the content of loadassets.js:

    var gameResources = [
         "assets/target.png"
    ];

    An array called gameResources stores the assets to preload. So, you should create a folder called assets and place the target.png image inside this folder.

    Note

    To keep the project organization clear, I am going to place all game assets in a folder called assets.

  2. Now that Cocos2d-JS is aware which images need to be preloaded, we only need to tell the game that it has to preload them before the scene starts, so we need to add a couple of lines to main.js:
    cc.game.onStart = function(){
      cc.view.setDesignResolutionSize(320, 480, cc.ResolutionPolicy.SHOW_ALL);
      cc.LoaderScene.preload(gameResources, function () {
        cc.director.runScene(new gameScene());
      }, this);
    };
    cc.game.run();

    The cc.LoaderScene.preload constructor will preload scene resources taken from the gameResources array defined in loadassets.js. All puzzle pieces match perfectly.

  3. Finally, let's add the target to the game by rewriting the gamescript.js file:
    var gameScene = cc.Scene.extend({
      onEnter:function () {
      this._super();
        var gameLayer = new game();
        gameLayer.init();
        this.addChild(gameLayer);
      }
    });
    var game = cc.Layer.extend({
      init:function () {
        this._super();
        var target = cc.Sprite.create("assets/target.png");
        this.addChild(target,0);
      }
    });

If you developed Flash games using AS3 (ActionScript 3), you will find Cocos2d-JS assets hierarchy familiar to display objects. If you are new to this, allow me to explain what happens:

  1. Like all frameworks that deal with graphic resources, Cocos2d-JS has hierarchy rules. On the top of such a hierarchy, we find the Scene object. Each scene contains some game logic; think about a main menu scene, a game scene, and a game over scene.
  2. Each scene contains one or more Layer objects; layers define which content should be at the top of other content. In a real-world example, a level background is in the bottom-most layer, player and enemies will be created in a layer above the background, and game information such as score and remaining lives are placed on the topmost layer.
  3. Finally, all layers can have one or more Sprite objects, which are the graphic assets themselves such as the player, the enemies, or in this case, the target.
  4. To summarize, the code means that once gameScene is executed, create and add the game layer, and in this layer, add the target sprite.

It's time to test the project by calling the index.html file, and the following screenshot is what you should get:

Preloading and adding images

Although it's just a basic project, there are several things to take note of:

  • Images are preloaded and a default loading screen is shown. This means the preloader works.
  • Although our project is set to work at 320x480, the game stretches to fill the browser completely, thanks to the resolution policy set before.
  • Images have their registration point in the center of the image, whereas most frameworks have their image registration point in the upper-left corner.
  • The origin (0,0) of the scene takes place in the lower-left corner, while most frameworks have their origin in the upper-left corner.

To top it all, you were able to create your first project. To change the target position and place it in the middle of the screen, just use the setPosition method that changes gamescript.js this way:

var gameScene = cc.Scene.extend({
  onEnter:function () {
  this._super();
    var gameLayer = new game();
    gameLayer.init();
    this.addChild(gameLayer);
  }
});

var game = cc.Layer.extend({
  init:function () {
    this._super();
    var target = cc.Sprite.create("assets/target.png");
    this.addChild(target,0);
    target.setPosition(160,240);
  }
});

Test the project and you will see the target image in the middle of the screen.

You have been reading a chapter from
Learning Cocos2d-JS Game Development
Published in: Jan 2015
Publisher:
ISBN-13: 9781784390075
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime