Home Game Development Learning Cocos2d-JS Game Development

Learning Cocos2d-JS Game Development

By Emanuele Feronato
books-svg-icon Book
eBook $19.99 $13.98
Print $32.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $19.99 $13.98
Print $32.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Hello World – A Cross-platform Game
About this book
Publication date:
January 2015
Publisher
Packt
Pages
188
ISBN
9781784390075

 

Chapter 1. Hello World – A Cross-platform Game

The legend says that the first working script you should do when learning a new language is the classic Hello World printed somewhere on the screen.

This chapter will guide you through the creation of a cross-platform Hello World example, covering these concepts:

  • The theory behind the creation of cross platform games

  • Cocos2d-JS installation and setup

  • A Cocos2d-JS project blueprint

  • Scenes, Layers, and Sprites

  • Preloading images

  • Adding images

  • Removing images

By the end of the chapter, you will be able to create a template project to create any kind of Cocos2d-JS cross-platform game that is capable of running on various devices at different resolutions.

 

Why should I make cross-platform games?


This is a very important question. I asked it to myself a lot of times when HTML5 mobile gaming started to become popular. I was just thinking it was a waste of time to simply care about the different screen resolutions and aspect ratios, so my first HTML5 game was made to perfectly fit my iPad 2 tablet.

When I finally showed it to sponsors, most of them said something like "Hey, I like the game, but unfortunately it does not look that good on my iPhone". "Don't worry", I said, "you'll get the game optimized for iPad and iPhone". Unfortunately, it did not look that good on the Galaxy Note. Neither did it on the Samsung S4.

You can imagine the rest of this story. I found myself almost rewriting the game with a series of if.. then.. else loops, trying to make it look good on any device.

This is why you should make a cross-platform game: To code once and rule them all. Focus on game development and let a framework do the dirty work for you.

 

What Cocos2d-JS is and how it works


Cocos2d-JS is a free open source 2D game framework. It can help you to develop cross-platform browser games and native applications. This framework allows you to write games in JavaScript. So, if you have already developed JavaScript applications, you don't have to learn a new language from scratch. Throughout this book, you will learn how to create almost any kind of cross-platform game using a familiar and intuitive language.

Requirements to run Cocos2d-JS

Before you start, let's see what software you need to install on your computer in order to start developing with Cocos2d-JS:

  • Firstly, you need a text editor. The official IDE for Cocos2d-JS coding is Cocos Code IDE, which you can download for free at http://www.cocos2d-x.org/products/codeide. It features auto completion, code hinting, and some more interesting characteristics to speed up your coding. If you are used to your favorite code editor, that's fine. There are plenty of them, but I personally use PSPad (you can find this at http://www.pspad.com/) on my Windows machine and TextWrangler (you can find this at http://www.barebones.com/products/textwrangler/) on the Mac. They are both free and easy to use, so you can download and have them installed in a matter of minutes.

  • To test your Cocos2d-JS projects, you will need to install a web server on your computer to override security limits when running your project locally. I am using WAMP (http://www.wampserver.com/) on my Windows machine, and MAMP (http://www.mamp.info/) on the Mac.

    Tip

    Again, both are free to use as you won't need the PRO version, which is also available for Mac computers. Explaining all the theory behind this is beyond the scope of this book, but you can find all the required information as well as the installation documentation on the official sites.

  • If you prefer, you can test your projects directly online by uploading them on an FTP space you own and call them directly from the web. In this case, you don't need to have a web server installed on your computer, but I highly recommend using WAMP or MAMP instead.

  • I personally use Google Chrome as the default browser to test my projects. As these projects are meant to be cross-platform games, it should run in the same way on every browser, so feel free to use the browser you prefer.

The latest information about Cocos2d-JS can be found on the official page http://www.cocos2d-x.org/wiki/Cocos2d-JS, while the latest version can be downloaded at http://www.cocos2d-x.org/download.

Note

Cocos2d-JS is updated quite frequently, but at the time of writing, the latest stable release is v3.1. Although new releases always bring some changes, all examples included in this book should work fine with any release marked as 3.x as there aren't huge changes in the roadmap.

You will notice the download file is a ZIP file that is greater than 250 MB. Don't worry. Most of the content of the package is made by docs, graphic assets, and examples, while the only required folder, at the moment, is the one called cocos2d-html5.

 

The structure of your Cocos2d-JS project


Every HTML5 game is basically a web page with some magic in it; this is what you are going to create with Cocos2d-JS: a web page with some magic in it.

To perform this magic, a certain file structure needs to be created, so let's take a look at a screenshot of a folder with a Cocos2d-JS project in it:

This is what you are going to build; to tell you the truth, this is a picture of the actual project folder I built for the example to be explained in this chapter, which is placed in the WAMP localhost folder on my computer. It couldn't be any more real.

So, let's take a look at the files to be created:

  • cocos2d-html5: This is the folder you will find in the zip archive.

  • index.html: This is the web page that will contain the game.

  • main.js:This is a file required by Cocos2d-JS with the Cocos2d-JS function calls to make the game start. You will create this within the next few minutes.

  • project.json: This is a JavaScript Object Notation (JSON) with some basic configurations. This is what you need to make your game run. Well, almost, because the actual game will be placed in the src folder. Let's see a few other things first.

 

Hello Cross-World


The time has come, the boring theory has ended, and we can now start coding our first project. Let's begin!

  1. Firstly, create a page called index.html in the root of the game folder and write this HTML code:

    <!DOCTYPE html>
      <head>
        <title>
          My Awesome game
        </title>
        <script src="cocos2d-html5/CCBoot.js" type="text/javascript">
    </script>
        <script src="main.js" type="text/javascript">
    </script>
      </head>
      <body style="padding:0;margin:0;background-color:#000000;">
      </body>
    </html>

    There's nothing interesting in it as it is just plain HTML. Let's take a closer look at these lines to see what is going on:

    <script src=" cocos2d-html5/CCBoot.js "></script>

    Here, I am including the Cocos2d-JS boot file to make the framework start:

    <script src="main.js"></script>

    From the preceding line, this is where we call the script with the actual game we are going to build. Next, we have the following code:

    <canvas id="gameCanvas"></canvas>

    This is the canvas we will use to display the game. Notice here that the canvas does not have a width and height, as they will be defined by the game itself.

  2. Next is the creation of main.js: the only file we will call from our main index.html page. This is more of a configuration file rather than the game itself, so you won't code anything that is game-related at the moment. However, the file you are going to build will be the blueprint you will be using in all your Cocos2d-JS games.

    The content of main.js is as follows:

    cc.game.onStart = function(){
        cc.view.setDesignResolutionSize(320, 480, cc.ResolutionPolicy.SHOW_ALL);
        cc.director.runScene(new gameScene());
    };
    cc.game.run();

    Don't worry about the code at the moment; it looks a lot more complicated than it really is. At the moment, the only line we have to worry about is the one that defines the resolution policy.

    Tip

    One of the most challenging tasks in cross-platform development is to provide a good gaming experience, no matter what browser or what device the game is running on. However, the problem here is that each device has its own resolution, screen size, and ratio.

    Cocos2d-JS allows us to handle different resolutions in a similar way web designers do when building responsive design. At the moment, we just want to adapt the game canvas to fit the browser window while targeting the most popular resolution, which is 320x480 (portrait mode). That's what this line does:

     cc.view.setDesignResolutionSize(320, 480, cc.ResolutionPolicy.SHOW_ALL);

    Using these settings, you should be pretty sure that your game will run on every device, although you will be working in a low resolution.

    Also, have a look at this line:

    cc.director.runScene(new gameScene());

    Basically, a Cocos2d-JS game is made by a scene where the game itself runs. There can be more scenes in the same game. Imagine a scene with the title screen, a scene with the game over screen, and a scene with the game itself. At the moment, you only have one scene called gameScene. Remember this name because you are going to use it later.

  3. Following this, the next required blueprint file you are going to build is project.json, which has some interesting settings. Let's take a look at the file first:

    {
      "debugMode" : 0,
      "showFPS" : false,
      "frameRate" : 60,
      "id" : "gameCanvas",
      "renderMode" : 0,
      "engineDir":"cocos2d-html5/",
    
      "modules" : ["cocos2d"],
    
      "jsList" : [
        "src/gamescript.js"
      ]
    }

    What do these lines mean? Let's see them one by one:

    • debugMode: This is the object key that determines the level of debug warnings. It has a range from 0 to 6. Leave it at 0 at the moment since the project is very simple and we won't make any errors.

    • showFPS: This object can be true or false; it shows or hides the FPS meter on the screen.

    • frameRate: This object sets the frame rate of your game. Set it to 60 to have a smooth game.

    • id: This is the DOM element that is required to run the game. Do you remember you gave your canvas the gameCanvas id? Here you are.

    • engineDir: This is the folder where Cocos2d-JS is installed.

    • modules: This object engines the modules to load. At the moment, we only need the basic Cocos2d library.

    • jsList: This is an array with the files used in the game. This means we are going to create our game in src/gamescript.js.

  4. Finally, we arrive at the game script itself. This is the one that will contain the actual game, gamescript.js, which at the moment is just a plain declaration of the game scene:

    var gameScene = cc.Scene.extend({
      onEnter:function () {
        this._super();
        console.log("my awesome game starts here");
      }
    });

    Here, you want to save everything and call index.html page from your localhost (refer to your WAMP or MAMP docs) in your browser. If you now open the developer console, you should see:

    my awesome game starts here

Congratulations! This means you have successfully managed to create a Cocos2d-JS template file to build your future games.

Let's build our first mini game at once!

 

Preloading and adding images


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

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:

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.

 

Removing images and changing the background color


Now you know how to add images you might also be interested in knowing how to remove them. It's really intuitive: you added images with the addChild method, so you are going to remove them with the removeChild method.

Moreover, we will change the background color by adding an actual background layer, which covers the entire scene with a solid color.

There are just a couple of lines to add to gamescript.js:

var gameScene = cc.Scene.extend({
  onEnter:function () {
  this._super();
    var gameLayer = new game();
    gameLayer.init();
    this.addChild(gameLayer);
  }
});
var backgroundLayer;
var game = cc.Layer.extend({
  init:function () {
    this._super();
    backgroundLayer = cc.LayerColor.create(new cc.Color(40,40,40,255), 320, 480);
this.addChild(backgroundLayer);
    var target = cc.Sprite.create("assets/target.png");
    backgroundLayer.addChild(target,0);
    target.setPosition(160,240);
setTimeout(function(){
    backgroundLayer.removeChild(target);
    }, 3000);
  }
});

In the preceding code, backgroundLayer is a new layer that will be filled with a new color with the RGBA format (in this case, a full opaque dark grey), which will also contain the target image.

After three seconds since its creation, the target is removed from backgroundLayer with the removeChild method.

 

Summary


In this chapter, you learned how to install, configure, and run your first Cocos2d-JS project. You also learned how to place images on the screen.

Placing more instances of the same object will be one of the topics covered in the next chapter, where you will also create your first game, so no looking yet!

Test yourself with an exercise by trying to put 10 targets on the screen at random positions.

About the Author
  • Emanuele Feronato

    Emanuele Feronato has been studying programming languages since the early 1980s, with a particular interest in game development. He has taught online programming for European Social Fund (ESF), and then founded a web development company in Italy. As a game developer, Emanuele developed Flash games sponsored by the biggest game portals and his games have been played more than 90 million times. He now ports most of them on mobile platforms and develops HTML5 games, which have been featured in the most important mobile web markets, such as Amazon. As a writer, he has worked as a technical reviewer for Packt Publishing and published the books Flash Game Development by Example and Box2D for Flash Games. His blog, www.emanueleferonato.com, is one of the most visited blogs about indie game development.

    Browse publications by this author
Learning Cocos2d-JS Game Development
Unlock this book and the full library FREE for 7 days
Start now