Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Building Android Games with Cocos2d-x
Building Android Games with Cocos2d-x

Building Android Games with Cocos2d-x: Learn to create engaging and spectacular games for Android using Cocos2d-x

eBook
Can$18.99 Can$27.99
Paperback
Can$34.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.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

Building Android Games with Cocos2d-x

Chapter 2. Graphics

In this chapter, we will cover how to create and handle all your game graphics. We will create the scenes, the transitions between those using the game director, create sprites, locate them in the desired position, move them around using actions, and bring our characters to life using animation.

The following topics will be covered in this chapter:

  • Creating scenes
  • Understanding nodes
  • Understanding sprites
  • Understanding actions
  • Animating sprites
  • Adding the game menus
  • Handling multiple screen resolutions

Creating scenes

The scene concept is very important within the Cocos2d-x game engine, since all the displayed screens in our game are considered scenes. Creating an analogy between Cocos2d-x and the Android native Java development, we can say that a Cocos2d-x scene is equivalent to what Android calls activity.

In the previous chapter we introduced the AppDelegate class, and we explained that it has the responsibility of loading the framework on the device and then executing the game-specific code. This class contains the ApplicationDidFinishLaunching method, which is the entry point of our code. In this method, we instantiate the scene that is going to first be displayed in our game, and then request the director to load it, as we can see in the following code listing:

bool AppDelegate::applicationDidFinishLaunching() {
    auto director = Director::getInstance();
  // OpenGL initialization done by cocos project creation script
    auto glview = director->getOpenGLView();
    auto scene...

Pausing the game

Let us start and create our game. The first feature that we are going to add is the functionality for pausing and resuming our game. Let's start building – we'll start by setting up the screen that will appear when we pause the game.

We will achieve this by adding a new pause scene to the scene stack. When this screen is removed from the stack, the HelloWorld scene will show up because it was the displayed screen before the pause scene was pushed into the scene stack. The following code listing shows how we can easily pause our game:

Organizing our resources files

When we created our Cocos2d-x project, some resources such as images and fonts have been added by default to the Resources folder of our project. We are going to organize them, so that it is easier to handle them. For that matter, we are going to create an Image folder in the Resources directory. In this new folder, we are going to put all our images. Later on in this chapter, we will explain how...

Understanding nodes

Node represents all the visible objects on the screen, it is, in fact, the superclass of all the scene elements, including the scene itself. It is the base framework class, and it has the basic methods that allow you to handle graphics characteristics, such as position and depth.

Understanding sprites

In our game, the sprites represent the images of our scenes, just like the background, the enemies, and our player.

Later in Chapter 4, User Input, we will add event listeners to the scenes, so that it can interact with the user.

Creating sprites

It is very easy to instantiate the Cocos2d-x core classes. We have seen that the scene class has a create method; similarly, the sprite class has a static method with the same name, as we can see in the following code snippet:

auto sprBomb = Sprite::create("bomb.png");

Cocos2d-x currently supports PNG, JPG, and TIF image formats for sprites; nevertheless, it is highly recommended that we use the PNG images, because of its transparency capabilities, which are not present in either the JPG or the TIF format, and also because of the image quality that is provided by this format in a fair file size. That is why you will see that all the Cocos2d-x-generated templates and samples use this image format.

Positioning sprites

Once...

Understanding actions

We can easily tell our sprites to perform concrete actions, such as jump, move, skew, and so on. It requires a few lines to get our sprites to execute the desired action.

Moving sprites

We can make our sprite move to a specific area of the screen by creating a MoveTo action and then making the sprite execute the action.

In the following code listing, we are making the bomb fall to the bottom of the screen by simply writing the following code lines:

  auto moveTo = MoveTo::create(2, Vec2(sprBomb->getPositionX(), 0 - sprBomb->getContentSize().height/2));
  sprBomb->runAction(moveTo);

We have created a moveTo node that will move the bomb sprite to the current horizontal position, but it will also move it to the bottom of the screen until it is not visible. In order to achieve this, we made it move to the y position of the negative half of the height of the sprite. Since the anchor point is set to the center point of the sprite, moving it to the negative half of its...

Creating scenes


The scene concept is very important within the Cocos2d-x game engine, since all the displayed screens in our game are considered scenes. Creating an analogy between Cocos2d-x and the Android native Java development, we can say that a Cocos2d-x scene is equivalent to what Android calls activity.

In the previous chapter we introduced the AppDelegate class, and we explained that it has the responsibility of loading the framework on the device and then executing the game-specific code. This class contains the ApplicationDidFinishLaunching method, which is the entry point of our code. In this method, we instantiate the scene that is going to first be displayed in our game, and then request the director to load it, as we can see in the following code listing:

bool AppDelegate::applicationDidFinishLaunching() {
    auto director = Director::getInstance();
  // OpenGL initialization done by cocos project creation script
    auto glview = director->getOpenGLView();
    auto scene...

Pausing the game


Let us start and create our game. The first feature that we are going to add is the functionality for pausing and resuming our game. Let's start building – we'll start by setting up the screen that will appear when we pause the game.

We will achieve this by adding a new pause scene to the scene stack. When this screen is removed from the stack, the HelloWorld scene will show up because it was the displayed screen before the pause scene was pushed into the scene stack. The following code listing shows how we can easily pause our game:

Organizing our resources files

When we created our Cocos2d-x project, some resources such as images and fonts have been added by default to the Resources folder of our project. We are going to organize them, so that it is easier to handle them. For that matter, we are going to create an Image folder in the Resources directory. In this new folder, we are going to put all our images. Later on in this chapter, we will explain how we are going to organize...

Understanding nodes


Node represents all the visible objects on the screen, it is, in fact, the superclass of all the scene elements, including the scene itself. It is the base framework class, and it has the basic methods that allow you to handle graphics characteristics, such as position and depth.

Understanding sprites


In our game, the sprites represent the images of our scenes, just like the background, the enemies, and our player.

Later in Chapter 4, User Input, we will add event listeners to the scenes, so that it can interact with the user.

Creating sprites

It is very easy to instantiate the Cocos2d-x core classes. We have seen that the scene class has a create method; similarly, the sprite class has a static method with the same name, as we can see in the following code snippet:

auto sprBomb = Sprite::create("bomb.png");

Cocos2d-x currently supports PNG, JPG, and TIF image formats for sprites; nevertheless, it is highly recommended that we use the PNG images, because of its transparency capabilities, which are not present in either the JPG or the TIF format, and also because of the image quality that is provided by this format in a fair file size. That is why you will see that all the Cocos2d-x-generated templates and samples use this image format.

Positioning sprites

Once we have created...

Left arrow icon Right arrow icon

Description

If you have a basic understanding of the C++ programming language and want to create videogames for the Android platform, then this technology and book is ideal for you.

Who is this book for?

If you have a basic understanding of the C++ programming language and want to create videogames for the Android platform, then this technology and book is ideal for you.

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 30, 2015
Length: 160 pages
Edition : 1st
Language : English
ISBN-13 : 9781785283833
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.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 : Mar 30, 2015
Length: 160 pages
Edition : 1st
Language : English
ISBN-13 : 9781785283833
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$ 158.97
Cocos2d-x cookbook
Can$61.99
Building Android Games with Cocos2d-x
Can$34.99
Cocos2d-x by example (update)
Can$61.99
Total Can$ 158.97 Stars icon

Table of Contents

9 Chapters
1. Setting Up Your Development Environment Chevron down icon Chevron up icon
2. Graphics Chevron down icon Chevron up icon
3. Understanding Game Physics Chevron down icon Chevron up icon
4. User Input Chevron down icon Chevron up icon
5. Handling Text and Fonts Chevron down icon Chevron up icon
6. Audio Chevron down icon Chevron up icon
7. Creating Particle Systems Chevron down icon Chevron up icon
8. Adding Native Java Code 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 Full star icon Half star icon 4.3
(8 Ratings)
5 star 25%
4 star 75%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Francis May 20, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I found this book very helpful in getting the latest Cocos2d-x 3.x running on my Android devices. The book provides very clear instructions on setting up the Android development environment such as the Android SDK, NDK and Eclipse tools. After the first chapter you will be able use the Cocos2d-x Android build process to deploy a simple application to your Android device.The book covers all the basics of Cocos2d-x in the next few chapters, covering graphics, game physics, user input, text display, audio and particle systems. This is done by walking the reader through the development of a simple game. Additional information for the Android platform is also included such as handling the Android key press events.The last chapter is the best part for Android developers as it demonstrates how to add native java code to your project and goes over the Java NativeInterface (JNI) capabilities that allows you to interface with popular banner providers such as Google AdMob.Overall this book is best for anyone wanting to use Cocos2d-x to deploy an application to Android devices and provides a good overview of Cocos2d-x. It seems to be targeted at the beginner and will give the read a good start in getting games deployed on Android devices using Cocos2d-x.
Amazon Verified review Amazon
Jaime Sierra May 20, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Few books in the world that is written in English to talk about Cocos2D-x, which is a powerful tool for writing code once and to have it on different platforms, in this book you can build an Android game, which has the difficulty of being used in multiple devices with different screen sizes, so it is especially important in the design for optimal user experience. One can also say "everything is on the Internet", but "step by step" training book "Building Android Games with Cocos2d-x" can learn "without gaps" and have a basis to create the app easier to you want to achieve.Recommended the book.
Amazon Verified review Amazon
CdrJameson Oct 11, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
A short book, but did exactly what I wanted and got my Cocos2d-x project off the ground in no time at all.Doesn't contain a great deal of further detail but saved me a good week or so of figuring out what was going on.
Amazon Verified review Amazon
Piotr Kuszyk May 22, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
The book is written for the Cocos2dx version 3.4. I am using 3.5 and I had no problems with the listings and the source code. The first chapter about setting up the environment is rely useful. I didn’t have problems on (Win 8.1). People with absolutely no experience might have problems with importing project into Eclipse. REMEMBER to import only project from proj.android directory. After that import cocos2d and select “libcocos2dx” only.The book guides you through creating a single simple game from scratch. Each chapter covers one issue and adds new functionality to the game. For a person with no experience in game development and Cocos2d it might be difficult to get familiar with the idea of Scenes or Layers. There is very little about it in second chapter.After understanding the idea of layers and scenes, the rest of the topics is more clear. At the beginning you learn how to move objects in the game and animate them. There is also described how to create a menu and animate between scenes.Game Physics seems to be described enough. You learn how to make things fall down. You apply force, velocity and torque to the object. You learn how to detect a collision.Events are also described quite well. You can learn how to deal with touch events and multi-touch events. You learn how to use accelerometer and how to handle the back button.The chapters about text and fonts, sound effects and particles are very entertaining. You learn how to apply plenty of effects to make the game look more professional.Last chapter about native java code shows how to add commercials to the game.Quick summarize:C++11 basics and Cocos2d basic concepts are required to fully understand the book. Good for beginners.PROS:1) Create fully functional game step by step2) Adding native Java code3) Cocos2d-x in version 3.4CONS:1) Only one physics engine described2) Macros and Director described too little3) Not explained how to remove sprites that are outside the screen (unused elements)4) Too little about particles
Amazon Verified review Amazon
Raul Roa Jul 01, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Cocos2d-X is a suite of open-source, cross-platform, game-development tools used by thousands of developers all over the world. It was branched out from the Cocos2d project in November 2010.It is a widely adopted framework among mobile developers and it is fair to say that an attempt to make a book about how to use it for Android development is a natural step.I must admit that after a weak foreword I was a bit skeptical about the quality of its content; after going through every chapter I changed my mind. The book is a good reference resource and if you are happen to be starting out, as a game developer trying to make your way at Google’s Playstore this might be a good place to start.The author makes an effort of breaking down the massive engine and it's most common features into digestible bits for anyone from novice to experts. It makes a pretty good job in going from installing a development environment from scratch to a working tech demo at the end of each chapter.Personally, I liked the way the author went into detail on describing how things work under the hood. However, I would have loved to see more depth into actual physics examples and a separated chapter that went into different collision detection strategies instead of cramping those up together.ConclusionBuilding Android Games with Cocos2d-x is a great introductory book for game developers who are looking to start on game development for Android mobile devices. It is also a great starting point for people who are looking into game development as a casual endeavor.I encourage you grab a copy right now!
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.