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 £16.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. £16.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781783985265
Vendor :
Apple
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. £16.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jul 27, 2015
Length: 392 pages
Edition : 1st
Language : English
ISBN-13 : 9781783985265
Vendor :
Apple
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
£16.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
£169.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
£234.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.