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
Cocos2d-X Game Development Blueprints
Cocos2d-X Game Development Blueprints

Cocos2d-X Game Development Blueprints: Build a plethora of games for various genres using one of the most powerful game engines, Cocos2d-x

eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

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

Cocos2d-X Game Development Blueprints

Chapter 2. How to Fly a Dragon!

This is the story of a dragon trapped inside a castle. You might ask why would a mighty creature like a dragon be trapped inside a castle. Well, obviously because he has deformed wings that are too small to carry his weight! It's our duty to help this poor creature out of this horrendous castle! We will continue using Cocos2d-html5 to create this charming game about a dragon trying to escape the bounds of the castle, with the player tapping to help the dragon fly. We'll call this game DragonDash.

In this chapter, you'll learn:

  • How to load a sprite sheet
  • How to create and use a cc.Animation
  • How to implement simple gravity and rectangular collision detection
  • How to play HTML5 audio and persistently store data in the browser

This is what we will achieve by the end of this chapter:

How to Fly a Dragon!

Getting to know sprite sheets

The first game we made was so simple that it just used a single image file. But the story of our dragon will need much more. So, we finally have enough art to actually collate it into a sprite sheet. As you may already know, a sprite sheet is an image that contains many other images. A sprite sheet needs a texture file and an information file to tell the engine where each individual image or frame lies within the texture. Since this is a fairly small game, you have just one sprite sheet that looks like this:

Getting to know sprite sheets

I created this sprite sheet and the corresponding plist using Texture Packer. Texture Packer is a great utility that helps you compose all of your sprite frames into a single sprite sheet. This is just one of the many things Texture Packer can do for you and your graphics artist. You can find Texture Packer and relevant information at the following URL:

https://www.codeandweb.com/texturepacker

You must load a sprite sheet into the cc.SpriteFrameCache if...

Creating a lively menu screen

The main menu needs to look something like this, but our dragon needs to be flying. Therefore, the castle wall and the backdrop should also move.

.

Creating a lively menu screen

Judging from the screenshot, you already know that we will be covering a major chunk of the game just creating this screen. Well, what can you do, our little dragon always wants to fly! So let's take some time and analyze the various things we need to do in order to accomplish the lively fairy tale menu screen.

Here are the things we need to implement:

  1. Create a dragon that can fly. Don't worry the frame animation takes care of that, we just need to move him!
  2. Create an environment with a background, some stars, and two continuously scrolling layers with a parallax effect.
  3. Create the basic UI.

Our first task dictates that we must create a dragon that can fly. This means our character must have an animation wherein it flaps its wings and some motion so that it moves upwards and downwards.

We will create the frame...

Creating a fairy tale

Since we are dealing with a dragon here, it seems only fair that the environment should also be out of a fairy tale. Hence, we will build our environment with a castle, a midnight sky full of twinkling stars, and a few dark silhouettes. Since we will need this exact same environment in our other major scene, that is, the game world, it's a good idea to separate it out into another class. Thus, we have the FairytaleManager class defined in the fairytaleManager.js file:

var MAX_SCROLLING_SPEED = 6;
var CASTLE_SPRITE_Y = -50;
var SILHOUETTE_SPRITE_Y = 100;
var MAX_STARS = 15;

function FairytaleManager(parent)
{
  // save reference to GameWorld
  this.parent = parent;
  this.screenSize = parent.screenSize;
  // initialise variables
  this.castleSpriteSize = cc.SIZE_ZERO;
  this.castleSprites = [];
  this.lastCastleIndex = 0;
  this.silhouetteSpriteSize = cc.SIZE_ZERO;
  this.silhouetteSprites = [];
  this.lastSilhouetteIndex = 0;
}

First, we declare a few global quantities...

Setting things into motion

We'll need to move the castle and the silhouettes to create an illusion of the dragon flying. We do this by updating their position after every tick, as shown here:

FairytaleManager.prototype.update = function() {
  this.updateCastle();
  this.updateSilhouette();
};

The update function will be called from the parent layer (MainMenu or GameWorld) on every tick. It is here that you will have to move your castle and the backdrop. The updateCastle and updateSilhouette functions are identical, so I will discuss the updateCastle function only:

FairytaleManager.prototype.updateCastle = function(){
  for(var i = 0; i < this.castleSprites.length; ++i)
  {
    // first update the position based on the scroll speed
    var castleSprite = this.castleSprites[i];
    castleSprite.setPosition(castleSprite.getPositionX() - MAX_SCROLLING_SPEED, castleSprite.getPositionY());

    // check if the sprite has gone completely out of the left edge of the screen
    if(castleSprite...

On to the game world

You already set the environment up in the last two sections. Now we need to code in some gameplay. So we add towers that the dragon must dodge and add some gravity as well as touch controls. All this action happens in our second scene, which goes by the name GameWorld and is defined in the gameworld.js file. The following are the member variables of gameworld.js:

// variables
screenSize:null,
spriteBatchNode:null,
score:0,
scoreLabel:null,
mustAddScore:false,
tutorialSprite:null,
popup:null,
castleRoof:0,
hasGameStarted:false,
// managers
towerManager:null,
dragonManager:null,
fairytaleManager:null,

You might remember some of the variables declared in the preceding code from the previous chapter. In addition, you can see some variables that record the position of the castle roof, if the game has started and if a score needs to be added. Finally, you will find three variables that will reference our respective managers.

In our first game, we coded all the game logic straight...

Getting to know sprite sheets


The first game we made was so simple that it just used a single image file. But the story of our dragon will need much more. So, we finally have enough art to actually collate it into a sprite sheet. As you may already know, a sprite sheet is an image that contains many other images. A sprite sheet needs a texture file and an information file to tell the engine where each individual image or frame lies within the texture. Since this is a fairly small game, you have just one sprite sheet that looks like this:

I created this sprite sheet and the corresponding plist using Texture Packer. Texture Packer is a great utility that helps you compose all of your sprite frames into a single sprite sheet. This is just one of the many things Texture Packer can do for you and your graphics artist. You can find Texture Packer and relevant information at the following URL:

https://www.codeandweb.com/texturepacker

You must load a sprite sheet into the cc.SpriteFrameCache if you...

Creating a lively menu screen


The main menu needs to look something like this, but our dragon needs to be flying. Therefore, the castle wall and the backdrop should also move.

.

Judging from the screenshot, you already know that we will be covering a major chunk of the game just creating this screen. Well, what can you do, our little dragon always wants to fly! So let's take some time and analyze the various things we need to do in order to accomplish the lively fairy tale menu screen.

Here are the things we need to implement:

  1. Create a dragon that can fly. Don't worry the frame animation takes care of that, we just need to move him!

  2. Create an environment with a background, some stars, and two continuously scrolling layers with a parallax effect.

  3. Create the basic UI.

Our first task dictates that we must create a dragon that can fly. This means our character must have an animation wherein it flaps its wings and some motion so that it moves upwards and downwards.

We will create the frame animation...

Creating a fairy tale


Since we are dealing with a dragon here, it seems only fair that the environment should also be out of a fairy tale. Hence, we will build our environment with a castle, a midnight sky full of twinkling stars, and a few dark silhouettes. Since we will need this exact same environment in our other major scene, that is, the game world, it's a good idea to separate it out into another class. Thus, we have the FairytaleManager class defined in the fairytaleManager.js file:

var MAX_SCROLLING_SPEED = 6;
var CASTLE_SPRITE_Y = -50;
var SILHOUETTE_SPRITE_Y = 100;
var MAX_STARS = 15;

function FairytaleManager(parent)
{
  // save reference to GameWorld
  this.parent = parent;
  this.screenSize = parent.screenSize;
  // initialise variables
  this.castleSpriteSize = cc.SIZE_ZERO;
  this.castleSprites = [];
  this.lastCastleIndex = 0;
  this.silhouetteSpriteSize = cc.SIZE_ZERO;
  this.silhouetteSprites = [];
  this.lastSilhouetteIndex = 0;
}

First, we declare a few global quantities...

Left arrow icon Right arrow icon

Description

If you are a proficient Cocos2d game developer who wants to enhance his or her game development skill set using Cocos2d-x to build different types of games, this book is for you.

Who is this book for?

If you are a proficient Cocos2d game developer who wants to enhance his or her game development skill set using Cocos2d-x to build different types of games, this book is for you.

What you will learn

  • Take advantage of the open source nature of Cocos2dx by extending the engine to customize and add your own features to it
  • Design games with levelbased and timebased difficulty progression, which are very addictive and keeps users engaged
  • Maximize user interaction by implementing intuitive gestures and tilt controls
  • Implement advanced physics engine features such as PreSolve and PostSolve events
  • Add realism to your game by using a touch event, and use it to control a game
  • Implement circletocircle collision detection in your games
  • Build the same project on multiple platforms, such as Android and Windows, effortlessly

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 27, 2015
Length: 392 pages
Edition : 1st
Language : English
ISBN-13 : 9781783985272
Vendor :
Apple
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 : Jul 27, 2015
Length: 392 pages
Edition : 1st
Language : English
ISBN-13 : 9781783985272
Vendor :
Apple
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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 €5 each
Feature tick icon Exclusive print discounts
€264.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 €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 115.97
Cocos2d-x cookbook
€36.99
Cocos2d-X Game Development Blueprints
€41.99
Cocos2d-x by example (update)
€36.99
Total 115.97 Stars icon
Banner background image

Table of Contents

11 Chapters
1. A Colorful Start Chevron down icon Chevron up icon
2. How to Fly a Dragon! Chevron down icon Chevron up icon
3. Not Just a Space Game Chevron down icon Chevron up icon
4. Back to the Drawing Board Chevron down icon Chevron up icon
5. Let's Get Physical! Chevron down icon Chevron up icon
6. Creativity with Textures Chevron down icon Chevron up icon
7. Old is Gold! Chevron down icon Chevron up icon
8. Box2D Meets RUBE Chevron down icon Chevron up icon
9. The Two Towers Chevron down icon Chevron up icon
10. Cross-platform Building Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(5 Ratings)
5 star 40%
4 star 40%
3 star 20%
2 star 0%
1 star 0%
Hugo Oct 12, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is awesome, it teaches me a lot, in an elegant way the author bring so many techniques to make simple clones of many successful mobile games, he has created a very useful introduction to not so simple games like in other books, this book can give you a really good base to make almost any kind of game. Ok could be better if he has used Cocos2d-x v3, but I don't know why he decides to do this in version 2, maybe in the time he has written the book, or he has more confidence in v2, whatever, isn't so difficult to use his techniques in the newest version of the engine, he did not simple show the tools, but he shows how to use the tools and what kind of result the tool makes you achieve. I think this book is the best book for Cocos2d-x, because isn't just introductory, this is a huge step for me as beginner, I really recommend this book!
Amazon Verified review Amazon
Jaime Sierra Silva (Consignment) Sep 08, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is useful for learning to program in framework Cocos2d-html5, many practical examples of game development of all types to see the versatility of programming Cocos2d-x offer games for Android, iOS, Windows Phone 8. Web and also teaches to use various complementary tools for your future developments such as, among others WebStorm and Eclipse. Finally, a book that complements knowledge to develop robust and unrivaled gaming experience for your future customers of your games.It is recommended to have some experience in Cocos2d-x and JavaScript.
Amazon Verified review Amazon
aseem gupta Jul 31, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Finally some intermediate-advance level cocos2d-x book has been published.And if you liked "cocos2d-x:by example beginner’s guide", then you will surely love this book more in terms of concepts covered.Giving 4 stars because concepts covered are good otherwise 3 stars.PROS:1. Games covered are not just bare bones like in almost all other books. Author has truly kept in mind that games covered should be having functionality that professional games have like progressive difficulty levels, XML level design for scalability, etc.2. Two basic games(similar to diamond digger saga but basic version and other is flappy birds clone) and rest games covered are either intermediate-advanced or approach to develop them is professional like XML levels, DrawNode API based games, etc3. Thanks for covering XML parsing which is needed for writing levels outside the code otherwise writing levels in arrays is inconvenient.3. How to add progression and difficulty levels is covered in later chapter.4. A big thanks for covering textures programatiCally for cocos2d-x which was used in famous game Tiny Wings. I don’t know Obj-C(cocos2d) because I don’t like it and was being lazy to understand this difficult tutorial at Raywenderlich’s website. Author’s have given link for those tutorials in the book, in case someone wants to see. And yes, this tutorial is difficult for me to understand. And not sure how to port it to v3.x of cocos2d-x because of draw APIs used are of version 2.x.5. I liked the last chapter which is a tower defense game and how XML levels designing and tile map is used. Also, there is no other better place to use fast and forward(scheduler API) than this kind of a game. Tile Based games has endless possibilities and you can have a great start with 2 games covered in the book.CONS:1. Old version of cocos2d-x (v2.2.x) use, so there can be difficulty in porting draw APIs to newer ones. Also, how to handle Box2D in v3.x is slight different but concepts are same. Concepts for touch listeners have changed but i think that won’t be much of a problem for old cocos2d-x programmers.2. I felt 'catapult string' thing missing that is originally present in angry birds game. But concepts of Box2D(like ray casts) are good. And sadly RUBE is paid(trial) software which is used for designing the levels.3. Some APIs are not covered like Parallax API, and few others though they are not required in majority of games.I still have to read the cross platform chapter!This would have been a great resource if cocos2d-x version used was 3.x but it’s must read book for programmers whose prime motto is to learn more concepts.And btw, cocos2d-x v2.x have also helped many programmers to make amazing cocos2d-x games so there is no question on the engine as such but obviously latest version can reduce the pain of writing code at certain places and APIs are somewhat better though engine is overall the same.Hope the book will be updated to latest cocos2d-x version.
Amazon Verified review Amazon
Francis Aug 02, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Even though this book is based on Cocos2d-x-2.2.5, its main concepts still apply for the latest 3.7 version. Several game examples are provided that demonstrate the core concepts of cocos2d-x.I am familiar with C++ version of Cocos2d-x, this book focuses on using JavaScript and Cocos2d-html5 in the first couple of chapters which provided me a good understanding of implementing a web based game using Cocos2d-html5.The code is well documented in the book and shown in small snippets to make it easier to understand. The Flappy Bird clone (DragonDash) demonstrates using sprite sheets and building an infinitely long castle in 20 lines of code. The author does a good job at breaking down core gameplay and showing how to implement this in JavaScript.By the chapter 3, the author has moved on to C++ version of the cocos2d-x engine to implement a space invaders type game. Some of the code presented would have to be updated for the latest 3.7 version but this is well documented on the cocos2d-x website. What the chapter does best is to show how to develop a game, the cocos2d-x is just the tool used to build the game.In chapter 5 the author demonstrates the basics of the popular physics engine, Box2D. The code is in C++ and would be familiar to any other implementation of Box2D, which there are many examples on internet.Tile-based games are popular and powerful in that there are many tile based editors that make it easy to develop levels for your game. Chapter 7 demonstrates making a simple platform game using Tiled Map Editor and Cocos2d-x C++.Chapter 8 the author shows how to implement a Angry Birds type game using RUBE, which is an IDE for designing Box2D physics based games, there are several tools like this available that support Cocos2d-x.The last game implemented in Chapter 9 is a tower defense game, which there are many examples on internet for Cococs2d-x. Using XML to describe the properties of the game is very useful and can be applied to many other type of games.The author closes with Chapter 10, Cross-platform building, which shows how to build Android and Windows Phone 8 projects. Some of this information has changed for the latest version of Cocos2d-x and is available on the official Cocos2d-x website.Many commercial games have been written with Cocos2d-x 2.2.x and some are staying with this version because of stability and a large code base. The newer version of Cocos2d-x 3.7 provides support for 3D and so much more. It would be great if the author provided the same detailed game development that highlights the new features in the latest version of Cocos2d-x.
Amazon Verified review Amazon
Jose M. Jul 29, 2015
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
The book would be great, if we were in 2013... I just don't understand why the author had used an older version of the framework. The book is based on Cocos2d-x-2.2.5, last week the 3.7 version was released. The version 3 of cocos is stable, faster, has c++11 support, new data structures, and it is easier. You could port the code but... is that what a customer want to do?
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.