Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Learning Cocos2d-JS Game Development
Learning Cocos2d-JS Game Development

Learning Cocos2d-JS Game Development: Learn to create robust and engaging cross-platform HTML5 games using Cocos2d-JS

Arrow left icon
Profile Icon Emanuele Feronato
Arrow right icon
Can$12.99 Can$33.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.9 (11 Ratings)
eBook Jan 2015 188 pages 1st Edition
eBook
Can$12.99 Can$33.99
Paperback
Can$41.99
Subscription
Free Trial
Arrow left icon
Profile Icon Emanuele Feronato
Arrow right icon
Can$12.99 Can$33.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.9 (11 Ratings)
eBook Jan 2015 188 pages 1st Edition
eBook
Can$12.99 Can$33.99
Paperback
Can$41.99
Subscription
Free Trial
eBook
Can$12.99 Can$33.99
Paperback
Can$41.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Learning Cocos2d-JS Game Development

Chapter 2. Adding Interactivity – The Making of a Concentration Game

By definition, a game is interactive in some way. Players have to be part of it by doing things. The simplest form of interactivity is clicking or touching tiles in the game.

A Concentration game is simple to explain, but it will cover some new and important concepts, such as:

  • Creating multiple instances of game assets
  • Extending classes to improve its capabilities. Actually, there are no classes in JavaScript, but they are emulated using variables and prototypes
  • Adding gradients
  • Making assets react to clicks and touches
  • Changing sprite images on the fly
  • Adding text labels
  • Removing sprites from the game

By the end of the chapter, you will be able to create a full Concentration game using space for customization.

As the project created in the previous chapter is more than just a Hello World game and rather acts as a blueprint for all your future projects, you'll start building our Concentration game out of the...

Creating multiple instances of game assets

The first thing you have to do in the making of a Concentration game is draw the tiles that you will use in the game. Here are the pictures used for the covered tiles and the eight different tiles that could be potentially matched, all saved in the assets folder, as explained in the previous chapter:

Creating multiple instances of game assets

Each tile is a 64 x 64 PNG file, where the covered tile is called cover.png, while the tile to be matched is named with a progressive number from 0 to 7: tile_0, tile_1, until tile_7. This is because the actual board tile values will be stored in an array whose values will range from 0 to 7, and it will be easy to assign value 0 to tile_0, value 1 to tile_1, and so on.

With these nine files in the assets folder, you are ready to load them, thanks to the loadassets.js file located in the src folder of our project:

var gameResources = ["assets/cover.png",
  "assets/tile_0.png",
  "assets/tile_1.png",
  "assets/tile_2...

Adding a gradient background

A quick and easy way to improve the background is to add a gradient. Most of the skies and sceneries you see in the background of your favorite games are just gradients.

You are going to add a gradient layer conveniently called gradient to the game simply by adding these two lines to gamescript.js:

var gameScene = cc.Scene.extend({
  // same as before
});

var game = cc.Layer.extend({
  init:function () {
    this._super();
    var gradient = cc.LayerGradient.create(cc.color(0,0,0,255), cc.color(0x46,0x82,0xB4,255));
    this.addChild(gradient);
    for(i=0;i<16;i++){
      var tile = cc.Sprite.create("assets/cover.png");
      this.addChild(tile,0);
      tile.setPosition(49+i%4*74,400-Math.floor(i/4)*74);
    }
  }
});

Gradient layer creation is made by the cc.LayerGradient.create method, which requires both the start and end gradient color in an RGBA (Red, Green, Blue, Alpha) format.

There are two things you need to notice about the lines that were...

Extending the Sprite class beyond its capabilities

When I say sometimes, I mean most of the time the default Cocos2d-JS classes do not let you do everything you need to do with them.

Although this might seem like a limit of Cocos2d-JS, it's one of its best features. You are provided with a basic set of classes you can extend the way you need to, meaning you can add new capabilities.

So, what does it really mean to extend a class? Imagine a real-world example: you're entering a bike shop and buying a mountain bike. Your mountain bike is a class; with this class, you can do everything you can actually do with a mountain bike, namely pedal and steer.

Unfortunately, you are a bit lazy and don't want to pedal all the time, so you buy a little motor and add it to your mountain bike. Now, you can still do everything you usually did with your bike, but you can also rest your legs, turn on the motor, and let it pedal on your behalf.

You just extended the mountain bike, created a motorized...

Making assets react to clicks and touches

There are two ways to pick a tile, irrespective of whether you are playing with a touch or mouse-driven device. You can tap on a tile or you can click on it.

Picking a tile as an initial attempt

No matter the way you use Cocos2d-JS, all in all you are creating cross-platform games. You have to tell Cocos2d-JS you are going to let the user touch or click on some tiles, so the MemoryTile class will change this way:

var MemoryTile  = cc.Sprite.extend({
  ctor:function() {
    this._super();
    this.initWithFile("assets/cover.png");
    cc.eventManager.addListener(listener.clone(), this);
  }
})

What just happened? You just added an event listener to the event manager. The event manager is the entity that triggers events fired by the game or by the player. The addListener method adds a listener to the event manager, but you don't have a listener at the moment. Let's create one:

var listener = cc.EventListener.create({
  event: cc.EventListener...

Changing sprite images on the fly

Let's now find out how to change sprite images.

Showing the tile picture

Once a tile is picked, it has to show its picture. Pictures are just a graphical representation of a tile value, which you initially store in an array called gameArray declared at the very beginning of a gamescript.js file:

var gameArray = [0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7];
vargameScene = cc.Scene.extend({
  onEnter:function () {
    // same as before
  }
});

Then, once you create a new tile, you can assign it a custom attribute called pictureValue with the value of the i-th element of gameArray:

var game = cc.Layer.extend({
  init:function () {
    this._super();
    var gradient = cc.LayerGradient.create(cc.color(0,0,0,255), cc.color(0x46,0x82,0xB4,255));
    this.addChild(gradient);
    for(i=0;i<16;i++){
      var tile = new MemoryTile();
      tile.pictureValue = gameArray[i];
      this.addChild(tile,0);
      tile.setPosition(49+i%4*74,400-Math.floor(i/4)*74);
    }
  }
...

Creating multiple instances of game assets


The first thing you have to do in the making of a Concentration game is draw the tiles that you will use in the game. Here are the pictures used for the covered tiles and the eight different tiles that could be potentially matched, all saved in the assets folder, as explained in the previous chapter:

Each tile is a 64 x 64 PNG file, where the covered tile is called cover.png, while the tile to be matched is named with a progressive number from 0 to 7: tile_0, tile_1, until tile_7. This is because the actual board tile values will be stored in an array whose values will range from 0 to 7, and it will be easy to assign value 0 to tile_0, value 1 to tile_1, and so on.

With these nine files in the assets folder, you are ready to load them, thanks to the loadassets.js file located in the src folder of our project:

var gameResources = ["assets/cover.png",
  "assets/tile_0.png",
  "assets/tile_1.png",
  "assets/tile_2.png",
  "assets/tile_3.png",
  "assets...

Adding a gradient background


A quick and easy way to improve the background is to add a gradient. Most of the skies and sceneries you see in the background of your favorite games are just gradients.

You are going to add a gradient layer conveniently called gradient to the game simply by adding these two lines to gamescript.js:

var gameScene = cc.Scene.extend({
  // same as before
});

var game = cc.Layer.extend({
  init:function () {
    this._super();
    var gradient = cc.LayerGradient.create(cc.color(0,0,0,255), cc.color(0x46,0x82,0xB4,255));
    this.addChild(gradient);
    for(i=0;i<16;i++){
      var tile = cc.Sprite.create("assets/cover.png");
      this.addChild(tile,0);
      tile.setPosition(49+i%4*74,400-Math.floor(i/4)*74);
    }
  }
});

Gradient layer creation is made by the cc.LayerGradient.create method, which requires both the start and end gradient color in an RGBA (Red, Green, Blue, Alpha) format.

There are two things you need to notice about the lines that were added:

  1. The...

Left arrow icon Right arrow icon

Description

If you are a Java developer who wants to learn about Java EE, this is the book for you. It's also ideal for developers who already have experience with the Java EE platform but would like to learn more about the new Java EE 7 features by analyzing fully functional sample applications using the new application server WildFly.

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 12, 2015
Length: 188 pages
Edition : 1st
Language : English
ISBN-13 : 9781784391546
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jan 12, 2015
Length: 188 pages
Edition : 1st
Language : English
ISBN-13 : 9781784391546
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Can$ 145.97
Cocos2d Game Development Essentials
Can$41.99
Cocos2d-x by example (update)
Can$61.99
Learning Cocos2d-JS Game Development
Can$41.99
Total Can$ 145.97 Stars icon
Banner background image

Table of Contents

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

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.9
(11 Ratings)
5 star 45.5%
4 star 18.2%
3 star 18.2%
2 star 18.2%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Hugo Dec 14, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
As a Learning Cocos2d-JS book, this is a spectacular book, the author give a lot of examples about engine features, you can start to make your gamesusing physics(Box2D and Chipmunk), endless runner, particle, virtual pads, swipe gestures, grid levels, etc.The JS port of the Cocos2d-X engine is good, and the author is a great writer (his blog is really awesome), but, some people talks about this cross platform powers of Cocos2d-JS, that is possible to use on web and on devices, I thought that the author could give more information about, I have few questions about native development and more about to publish on web... and I'm not a complete beginner on Cocos2d-x C++ version, but the Cocos2d-x community is so active that all my questions about Android side was solved, but for web I am just starting, all examples run in every platform, you just need to know how to do it, isn't just HTML5, after you know how to use this engine for each platform in command line, isn't so complicated and it is on README file on root folder, you will see how powerful this book is and after that you will simply love it, as the title says "Learning Cocos2d-JS", this book is a powerful tool to you learn to make games, Cocos2d-JS is really fast for test, for my games the stability and performance was almost like native.
Amazon Verified review Amazon
iPaul Mar 23, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a good intro to game development if you are a JavaScript programmer, if you are a JavaScript beginner you should probably learn some JS (there are a lot of free intros online). The author will hold your hand into building a complete cross platform game while teaching you the in and outs of Cocos2d-JS (the JavaScript version of Cocos2d-x).
Amazon Verified review Amazon
Pradyumna Mar 25, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have worked with Cocos2D on iOS and have planned to develop cross platform games using some framework. That is when I got to know about Cocos2d-JS and this book gives you a clear cut explanation and a good flow on how to carry on with developing games and there are types of games that will be explained in the book. Thanks to Emanuele (Y)..
Amazon Verified review Amazon
Andrew McNutt Jan 27, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This was a fantastic book. There are a couple errors on the Kindle edition(the version I bought) but the code examples are all there. The different chapters each provide very useful information. I look forward to other books from this author.A little more on the book itself. This is great if you are completely new to Cocos2d-js(as I was). After reading the book I feel it gave me a solid base as to where to dive deeper on certain topics for a game I am working on. If you are new to Cocos2d-js it is well worth the money.
Amazon Verified review Amazon
CH Tan Mar 23, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It is a good book for the beginner to learn game programming theory with the examples. (I'm new to game programming)For me it still require the beginner to learn some basic knowledge of Javascript before get into this.The explanation after the code line by line, able to help the reader understand it clearly.That was less book teach about the Cocos2d-JS right now on the market. Will looking for more books about Cocos2d-JS programming books from Emanuele Feronato. Hope will release the Advanced Game Development soon.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.