Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
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

Arrow left icon
Profile Icon Raydelto Hernandez
Arrow right icon
Can$18.99 Can$27.99
Book Mar 2015 160 pages 1st Edition
eBook
Can$18.99 Can$27.99
Print
Can$34.99
Subscription
Free Trial
Arrow left icon
Profile Icon Raydelto Hernandez
Arrow right icon
Can$18.99 Can$27.99
Book Mar 2015 160 pages 1st Edition
eBook
Can$18.99 Can$27.99
Print
Can$34.99
Subscription
Free Trial
eBook
Can$18.99 Can$27.99
Print
Can$34.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Building Android Games with Cocos2d-x

Chapter 1. Setting Up Your Development Environment

In this chapter, we will explain how to download and set up all the required tools to get you started with setting up an environment for building games for the Android platform. Although there are huge similarities between the Mac OS and the Windows development environment, we will cover all the details regarding the installation in both of these operating systems.

The following topics will be covered in this chapter:

  • Cocos2d-x overview

  • Setting up Java

  • Setting up the Android SDK

  • Setting up the Android Native Development Kit (NDK)

  • Setting up Apache Ant

  • Setting up Python

  • Setting up Cocos2d-x

  • Setting up the Eclipse IDE

  • Template code walk-through

Cocos2d-x overview


Cocos2d-x is a C++ cross-platform port of the popular iOS gaming framework Cocos2d. It was first released in November 2010, and bought in 2011 by Chukong Technologies, a Beijing-based mobile gaming company. Nevertheless, it is still maintained by an active community of more than 400,000 developers worldwide, including Ricardo Quesada, the creator of the original Cocos2d iPhone engine.

This framework encapsulates all the game details, such as sound, music, physics, user inputs, sprites, scenes, and transitions, so the developer will only have to focus on the game logic rather than re-inventing the wheel.

Setting up Java


The Android platform technology stack is based on the Java technology; that is why the first item to be downloaded will be the Java Development Kit (JDK). Although Java JDK 8 is the latest version at the time of writing this book, it is not officially supported by all Android versions, so we will download JDK 6, all the template Java codes generated by Cocos2d-x can be successfully compiled with this version.

Note

Java Runtime Environment (JRE) is not enough for building the Android applications, since it only contains the files required for running the Java applications, but it does not contain the tools required for building the Java applications.

You can download the JDK 6 from Oracle at http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase6-419409.html regardless of your development environment.

If Windows is your current environment, then after installing JDK you are required to add the path of the binaries folder to the PATH environment variable. This path will look like this: C:\Program Files\Java\jdk1.6.0_45\bin.

Open a new system console and type javac –version, if Java compiler's version number is displayed, then you have successfully installed JDK in your system.

Note

JDK 7 is required for building the applications for Android 5.0 and higher. You should download this version if you are targeting the latest Android versions. But, if you want your game to be compatible with the Android versions that are older than 4.4, then you should pick JDK 6.

Setting up the Android SDK


The Android SDK contains all the required command line tools for building an Android application. It has versions for Windows, Mac, and GNU/Linux operating systems.

Android Studio is now the only officially supported IDE; nevertheless, Cocos2d-x 3.4 provides only out-of-the-box support for Eclipse, which was the former official IDE for Android development. It is no longer available for downloading, since it is not in active development any more, but you may download Eclipse manually and install the Android Development Tools (ADT) by following the steps below.

Downloading the Android SDK

You can download Android SDK from the link: http://developer.android.com/sdk. At the bottom of the page, under Other Download Options, you will find the option for downloading the SDK tools. Choose the version that matches your operating system.

At the time of writing this book, the latest version of SDK was 24.0.2.

Run the Android SDK Installer and install the Android SDK on your computer.

When the Android SDK finishes installing, it is not yet ready to build the Android apps. So, at the final screen of the installation wizard, mark the checkbox for Start SDK Manager so you can download the required components for building your games, as shown in the following screenshot:

Once the Android SDK Manager starts, select Android SDK Platform-tools and Android SDK Build-tools from the Tools folders. Then select SDK Platform from your desired API level, as shown in the following screenshot:

Downloading Eclipse

Download the latest version of the Eclipse IDE for Java Developers from http://www.eclipse.org/downloads. It will suggest the download versions compatible with your current operating system, select the version that better suits your operating system platform which will either be 32-bit or 64-bit.

At the time of writing this book, Eclipse Luna (4.4.1) was the latest version.

Setting up the Eclipse ADT plugin

Open Eclipse and navigate to Help | Install new Software and add the Eclipse ADT download location, which is https://dl-ssl.google.com/android/eclipse/, as shown in the following screenshot:

Click on OK, then select the Developer Tools checkbox, and click on Next in order to finish the ADT installation wizard.

Setting up the Android Native Development Kit


We have already downloaded the Android SDK that allows you to create Android applications using the Java Technology; nevertheless, the Cocos2d-x framework is written in C++, so you will need the Android Native Development Kit (NDK) in order to build the C++ code for the Android platform.

Note

Android's official documentation clearly states that you should use this native kit for specific circumstances, but you should not use it just because you are familiar with the C++ language, or because you want your application to perform faster. The manufacturer makes this suggestion because the Android core API is only available for Java.

Download the latest NDK revision. At the time this book was written, it was 10d. This version of NDK will allow you to build for all the Android platforms, including the latest.

You can download the latest version of the Android NDK for all the platforms from the following link:

https://developer.android.com/tools/sdk/ndk

After downloading it, run the executable file. It will decompress the Android NDK directory on the current path; you need to be aware of this path since you will need it later.

Setting up Apache Ant


Apache Ant is a build management tool widely used for automating the Java projects build process. It has been introduced in Cocos2d-x 3.0 for building the framework for the Android platform. It has made the Android build process simpler and enhanced the cross-platform build. Back in Cocos2d-x 2.x, building the Android apps within the Windows operating system required simulating the UNIX environment by using Cygwin. This required minor hacks for successfully building the code, many of them still remain undocumented on the official Cocos2d-x site.

This tool can be downloaded from the link: https://www.apache.org/dist/ant/binaries/

At the time of writing this book, version 1.9.4 was the latest. This tool is a cross-platform tool so a single download will work on any operating system that provides support for the Java technology.

In order to install this tool, just unzip the file. Remember the path since you will need it during the Cocos2d-x setup process.

Setting up Python


All the Cocos2d-x configuration files are written in Python. If you are using Mac OS or any Linux distribution, it will already be installed on your OS. So, you can skip this section.

If you are using Windows, you need to download Python 2 from the following link: https://www.python.org/ftp/python/2.7.8/python-2.7.8.msi.

Take in to consideration that Python, as Cocos2d-x, keeps simultaneous support for versions 2 and 3. Cocos2d-x only supports Python 2. At the time of writing this book the latest version of the 2 branch was 2.7.8.

After the installer finishes with the setup, you should manually add the Python installation path to the PATH environment variable. The default installation path is C:\Python27.

Open a new system console and type python, if the Python console is shown, as seen in the following screenshot, then it means that Python has been installed correctly:

Note

For setting an environment variable on Windows, click on the Start button and type: edit the system environment variables, click on it and hit the Environment Variables button, and then the environment variables configuration dialog will be displayed.

Setting up Cocos2d-x


Now that you have all the Cocos2d-x pre-requisites for building your first game for the Android platform, you are going to download the Cocos2d-x 3.4 framework and set it up with the help of the following steps:

  1. You can download the source code from http://www.cocos2d-x.org/download. Be aware that this page also has the link for downloading the Cocos2d-x branch 2, which is not covered in this book, and the manufacturer has officially announced that the new features will only be available in branch 3.

  2. After downloading the compressed Cocos2d-x source code, uncompress it to your desired location.

  3. In order to configure Cocos2d-x, open your system terminal and point to the path where you have uncompressed it, and type setup.py. It will require you to specify ANDROID_NDK_PATH, here you will specify the root directory of the NDK that you have previously uncompressed in the previous sections. Secondly, it will require you to specify ANDROID_SDK_ROOT, here you will specify the directory path from where you have chosen to install the Android SDK during the installation process. Then, it will require you to set ANT_ROOT, where you will specify the root directory of your ant installation. Finally, close the terminal, and open a new one so that the changes can take effect.

Creating your first project

Now, Cocos2d-x is set up, and it is ready for creating your first project. You can do so by typing the following command:

 cocos new MyGame -p com.your_company.mygame -l cpp -d NEW_PROJECTS_DIR

This script has created an Android template code for your game that will run in all the Android devices containing the Android API 9 or higher, that is Android 2.3 (Gingerbread) and later.

Take in to consideration that the package name should contain exactly two dots, as the example shows, if it has less or more, then the project creation script will not work. The –l cpp parameter means that the new project is going to use C++ as the programming language, which is the only one that is covered in this book.

Cocos2d-x 3.x, as opposed to branch 2.x, allows you to create your project outside of the framework directory structure. Therefore, you can create your project at any location, and not just inside the projects directory, as it was in the previous versions.

It will take a while, since it will copy all the framework files to your new project's path. After it finishes, plug your Android device to your computer, then you can easily run the template HelloWorld code by typing the following command within your new project's path:

cocos run -p android

Alternatively, you could run the following command regardless of your current path on the terminal:

cocos run -p android /path/to/project

Note

For building and running Cocos2d-x 3.4 for Windows, you will need Microsoft Visual Studio 2012 or 2013.

Now, you should be able to see the Cocos2d-x logo and a text that says Hello World, as we can see in the following image:

Setting up the Eclipse IDE

Cocos2d-x branch 3 has improved the Android building process significantly.

Back in branch 2, it was necessary to manually configure many environment variables within IDE, import many core projects, and handle dependencies. Even after completing all the steps, the Cygwin Windows UNIX port integration with Eclipse was never polished to work flawlessly, so minor hacks were required.

Building Cocos2d-x 3.4 within Eclipse is as simple as importing the project and clicking on the Run button. In order to achieve this, within the ADT, navigate to File | Import | General | Existing Projects into Workspace, select the path, where Cocos2d-x has created the new project from the previous sections. Then click on Finish.

Tip

Cocos2d-x Android template project is created using the API Level 10 as target platform. If you don't have this version installed on your system, you should change it by right-clicking on the project from the package explorer, click on Properties, and select your preferred installed Android API version from the Project Build Target box.

Now, right-click on the project name in the package explorer, click on run as, and finally, click on Android Application. The following pop up will be displayed, and it will require you to specify the Android device on which you want to launch the Cocos2d-x game:

After picking your Android device, you will see the HelloWorld game scene as it was shown when we ran the Run command in the previous section.

Template code walk-through


In this section, we will explain the main parts of the Cocos2d-x template code generated in the previous sections by the project creation script.

Java classes

We now have one Java class in our project named AppActivity that has no members and extends the Cocos2dxActivity class from the core library. We can also see that 22 Java classes from the core library have been referenced in the project. This code is aimed to make our C++ code work, and we don't have to modify it at all.

Android application configuration

The generated AndroidManifest.xml, which is the android configuration file, requires the permission android.permission.INTERNET, which allows your Android application to use the Internet connection on your device; nevertheless, this is not needed by our simple game code since there is no Internet interaction. So, you may delete this line from the AndroidManifest.xml file if you wish. Your game will be shown in landscape by default, but if you wish to create a game that runs in portrait mode, then you should change the android:screenOrientation value from landscape to portrait.

In order to change the Android application name, you may modify the app_name value located on the strings.xml file; it will affect the launcher icon's text and the application identifier within the Android OS.

When you are creating your own games, you will have to create your own classes, and those will often be more than the two classes that were created by the script. Every time you create a new class, you need to add its name to the LOCAL_SRC_FILES property of the Android.mk make file located inside the jni folder of your new project directory structure. So, when your cpp code is built by the C++ build tools, it knows which files it should compile.

C++ classes

Two C++ classes have been created: AppDelegate and HelloWorldScene. The first one is in charge of launching the Cocos2d-x framework and passing the control to the developer. The framework loading process happens within this class. If the Cocos2d-x core framework is successfully launched on the target device, it will run the applicationDidFinishLaunching method, which is the first game-specific function to be run.

The code is very straightforward and it is documented such that you will be able to grasp its logic easily. Our first minor change to the code will be to hide the debug information that shows by default on this sample game. You could simply guess that in order to achieve this you should only send false as a parameter for the setDisplayStats method call in the director singleton instance, as we can see in the following code listing:

bool AppDelegate::applicationDidFinishLaunching() {
    // initialize director
    auto director = Director::getInstance();
    auto glview = director->getOpenGLView();
    if(!glview) {
        glview = GLViewImpl::create("My Game");
        director->setOpenGLView(glview);
    }
    // turn on display FPS
    director->setDisplayStats(false);
    // set FPS. the default value is 1.0/60 if you don't call this
    director->setAnimationInterval(1.0 / 60);
    // create a scene. it's an autorelease object
    auto scene = HelloWorld::createScene();
    // run
    director->runWithScene(scene);
    return true;
}

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Scenes

As we will cover in the chapters later in this book, Cocos2d-x handles the scene concept just like movies; movies are composed by scenes, so are the Cocos2d-x games. We can visualize the different screens, such as loading, main menu, world selection, gameplay levels, ending credits, and so on, as the different scenes. Each scene has a class that defines its behavior. The template code has only one scene named HelloWorld scene that is initialized and launched from within the AppDelegate class. The scene flow is managed by the game director as we have seen in the previous code. The Director class has all the basic features to drive the game, just like a director does during a movie. There is a single shared instance of the director class that is used within the whole application scope.

HelloWorldScene contains the layer that represents all the visible areas that show up when we run our HelloWorld application, that is, the hello world label, the Cocos2d-x logo, and the menu showing the exit option.

Within the init method, we do the instantiation of the visual elements, and then we add it to the scene using the addChild method inherited from the Node core class.

Summary


In this chapter, we have introduced the Cocos2d-x 3.4 gaming framework, and explained how to download and install it. We have also explained all of its pre-requisites. We have configured our work environment, launched our first Android application into an actual device, and gone through a quick code overview of the main aspects of the template code generated by the script.

In the next chapter, we will cover how to create and manipulate all of our game graphics, such as the main character, enemies, obstacles, backgrounds, and so on.

Left arrow icon Right arrow icon

Key benefits

What you will learn

Product Details

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

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

Product Details

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

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$ 88.95 127.97 39.02 saved
Cocos2d-x Cookbook
Can$34.98 Can$49.99
Building Android Games with Cocos2d-x
Can$18.99 Can$27.99
Cocos2d-x by Example: Beginner's Guide
Can$34.98 Can$49.99
=
Book stack Total Can$ 88.95 127.97 39.02 saved Stars icon

Table of Contents

16 Chapters
Building Android Games with Cocos2d-x Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
Foreword Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
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
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.