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
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
€10.99 €16.99
Paperback
€20.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
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.
Estimated delivery fee Deliver to Malta

Premium delivery 7 - 10 business days

€32.95
(Includes tracking information)

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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Malta

Premium delivery 7 - 10 business days

€32.95
(Includes tracking information)

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
€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 94.97
Cocos2d-x cookbook
€36.99
Building Android Games with Cocos2d-x
€20.99
Cocos2d-x by example (update)
€36.99
Total 94.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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela