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! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Cocos2d-x by example (update)
Cocos2d-x by example (update)

Cocos2d-x by example (update): Unleash your inner creativity with the popular Cocos2d-x framework and learn how to build great cross-platform 2D games with this Cocos2dx tutorial

eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.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

Cocos2d-x by example (update)

Chapter 2. You Plus C++ Plus Cocos2d-x

This chapter will be aimed at two types of developers: the original Cocos2d developer who is scared of C++ but won't admit it to his friends and the C++ coder who never even heard of Cocos2d and finds Objective-C funny looking.

I'll go over the main syntax differences Objective-C developers should pay attention to and the few code style changes involved in developing with Cocos2d-x that C++ developers should be aware of. But first, a quick introduction to Cocos2d-x and what it is all about.

You will learn the following topics:

  • What Cocos2d-x is and what it can do for you
  • How to create classes in C++
  • How to memory manage your objects in Cocos2d-x and C++
  • What you get out of Ref

Cocos2d-x – an introduction

So what is a 2D framework? If I had to define it in as few words as possible, I'd say rectangles in a loop.

At the heart of Cocos2d-x, you find the Sprite class and what that class does, in simple terms, is keep a reference to two very important rectangles. One is the image (or texture) rectangle, also called the source rectangle, and the other is the destination rectangle. If you want an image to appear in the center of the screen, you will use Sprite. You will pass it the information of what and where that image source is and where on the screen you want it to appear.

There is not much that needs to be done to the first rectangle, the source one; but there is a lot that can be changed in the destination rectangle, including its position on the screen, its size, opacity, rotation, and so on.

Cocos2d-x will then take care of all the OpenGL drawing necessary to display your image where you want it and how you want it, and it will do so inside a render...

The class interface

This will be done in a .h file. We'll use a text editor to create this file since I don't want any code hinting and autocompletion features getting in the way of you learning the basics of C++ syntax. So for now at least, open up your favorite text editor. Let's create a class interface!

Time for action – creating the interface

The interface, or header file, is just a text file with the .h extension.

  1. Create a new text file and save it as HelloWorld.h. Then, enter the following lines at the top:
    #ifndef __HELLOWORLD_H__
    #define __HELLOWORLD_H__
    #include "cocos2d.h" 
  2. Next, add the namespace declaration:
    using namespace cocos2d;
  3. Then, declare your class name and the name of any inherited classes:
    class HelloWorld : public cocos2d::Layer {
    
  4. Next, we add the properties and methods:
    protected:
    int _score;
    
    public:
    
        HelloWorld();
        virtual ~HelloWorld();
    
        virtual bool init();
        static cocos2d::Scene* scene();
        CREATE_FUNC(HelloWorld);
        void update(float dt);
        inline int addTwoIntegers (int one, int two) {
            return one + two;
        }
    };
  5. We finish by closing the #ifndef statement:
    #endif // __HELLOWORLD_H__

What just happened?

You created a header file in C++. Let's go over the important bits of information:

  • In C++ you include, you do not import...

The class implementation

This will be done in a .cpp file. So let's go back to our text editor and create the implementation for our HelloWorld class.

Time for action – creating the implementation

The implementation is a text file with the .cpp extension:

  1. Create a new text file and save it as HelloWorld.cpp. At the top, let's start by including our header file:
    #include "HelloWorld.h"
  2. Next, we implement our constructor and destructor:
    HelloWorld::HelloWorld () {
        //constructor
    }
    
    HelloWorld::~HelloWorld () {
        //destructor
    }
  3. Then comes our static method:
    Scene* HelloWorld::scene() {
        auto scene = Scene::create();
        
        auto layer = HelloWorld::create();
    
        scene->addChild(layer);
    
        return scene;
    }
  4. And then come our two remaining public methods:
    bool HelloWorld::init() {
        // call to super
        if ( !Layer::init() )
        {
            return false;
        }
        
        //create main loop 
        this->scheduleUpdate();
        
        return true;
    }
    
    void HelloWorld::update (float dt) {
        //the main loop
    }

What just happened?

We created the implementation for our HelloWorld class. Here are the most important bits to take...

Instantiating objects and managing memory

There is no Automatic Reference Counting (ARC) in Cocos2d-x, so Objective-C developers who have forgotten memory management might have a problem here. However, the rule regarding memory management is very simple with C++: if you use new, you must delete. C++11 makes this even easier by introducing special pointers that are memory-managed (these are std::unique_ptr and std::shared_ptr).

Cocos2d-x, however, will add a few other options and commands to help with memory management, similar to the ones we have in Objective-C (without ARC). This is because Cocos2d-x, unlike C++ and very much like Objective-C, has a root class. The framework is more than just a C++ port of Cocos2d. It also ports certain notions of Objective-C to C++ in order to recreate its memory-management system.

Cocos2d-x has a Ref class that is the root of every major object in the framework. It allows the framework to have autorelease pools and retain counts, as well other Objective...

What you get with Ref

With Ref you get managed objects. This means that Ref derived objects will have a reference count property, which will be used to determine whether an object should be deleted from memory or not. The reference count is updated every time an object is added or removed from a Cocos2d-x collection object.

For instance, Cocos2d-x comes with a Vector collection object that extends the functionality of the C++ standard library vector (std::vector) by increasing and decreasing the reference count when objects are added and removed from it. For that reason, it can only store Ref derived objects.

Once again, every Ref derived class can be managed the way things used to be managed in Objective-C before ARC- with retain counts and autorelease pools.

C++, however, comes packed with its own wonderful dynamic list classes, similar to the ones you would find in Java and C#. But for Ref derived objects, you would probably be best served by Cocos2d-x managed lists, or else remember to...

Cocos2d-x – an introduction


So what is a 2D framework? If I had to define it in as few words as possible, I'd say rectangles in a loop.

At the heart of Cocos2d-x, you find the Sprite class and what that class does, in simple terms, is keep a reference to two very important rectangles. One is the image (or texture) rectangle, also called the source rectangle, and the other is the destination rectangle. If you want an image to appear in the center of the screen, you will use Sprite. You will pass it the information of what and where that image source is and where on the screen you want it to appear.

There is not much that needs to be done to the first rectangle, the source one; but there is a lot that can be changed in the destination rectangle, including its position on the screen, its size, opacity, rotation, and so on.

Cocos2d-x will then take care of all the OpenGL drawing necessary to display your image where you want it and how you want it, and it will do so inside a render loop. Your code...

Left arrow icon Right arrow icon

Description

If you are a game enthusiast who would like to develop and publish your own game ideas onto different app stores, this is the book for you. Some knowledge of C++ or Java is helpful but not necessary.

Who is this book for?

If you are a game enthusiast who would like to develop and publish your own game ideas onto different app stores, this is the book for you. Some knowledge of C++ or Java is helpful but not necessary.

What you will learn

  • Add timesaving and funlooking animations to your projects
  • Make your games look cooler with particle effects
  • Draw lines, circles, and other primitives on the screen
  • Create place holder sprites to quickly test your game ideas
  • Load external data into your games
  • Create projects and deploy them to iOS and Android
  • Prepare your game for a variety of screen sizes and resolutions
  • Use the CocosIDE and the Lua bindings to develop a game
Estimated delivery fee Deliver to Ecuador

Standard delivery 10 - 13 business days

$19.95

Premium delivery 3 - 6 business days

$40.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 26, 2015
Length: 270 pages
Edition : 1st
Language : English
ISBN-13 : 9781785288852
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 Ecuador

Standard delivery 10 - 13 business days

$19.95

Premium delivery 3 - 6 business days

$40.95
(Includes tracking information)

Product Details

Publication date : Mar 26, 2015
Length: 270 pages
Edition : 1st
Language : English
ISBN-13 : 9781785288852
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 $5 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 $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 152.97
Cocos2d-x by example (update)
$48.99
Cocos2d-X Game Development Blueprints
$54.99
Cocos2d-x cookbook
$48.99
Total $ 152.97 Stars icon
Banner background image

Table of Contents

13 Chapters
1. Installing Cocos2d-x Chevron down icon Chevron up icon
2. You Plus C++ Plus Cocos2d-x Chevron down icon Chevron up icon
3. Your First Game – Air Hockey Chevron down icon Chevron up icon
4. Fun with Sprites – Sky Defense Chevron down icon Chevron up icon
5. On the Line – Rocket Through Chevron down icon Chevron up icon
6. Quick and Easy Sprite – Victorian Rush Hour Chevron down icon Chevron up icon
7. Adding the Looks – Victorian Rush Hour Chevron down icon Chevron up icon
8. Getting Physical – Box2D Chevron down icon Chevron up icon
9. On the Level – Eskimo Chevron down icon Chevron up icon
10. Introducing Lua! Chevron down icon Chevron up icon
A. Vector Calculations with Cocos2d-x Chevron down icon Chevron up icon
B. Pop Quiz Answers 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.9
(10 Ratings)
5 star 90%
4 star 10%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




iPaul May 29, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good introduction to Cocos2d-x, you need to an expert C++ programmer though. Also, because of the cocos2d-x history it will help if you at least have an idea of how Objective-C works.
Amazon Verified review Amazon
Hugo Mar 14, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book showed me that the code doesn't need to be too complicated to make a good and fun game. This version of Cocos2d-x is much more simple, if you never have tried in a game project before, you can be happy, is the right time to use it, this framework is mature, easy to understand, with a ton of resources to learn how it works, a big variety tools to do more in games and publish, but, if you already know how this framework works or if you are an experienced game developer, this book will show you how good and easy can be make really good games, the examples showed in this book are full of functionalities to make great games, you can translate your knowledge easy and fast, this framework support C++, JavaScript and Lua, the main focus on the book is C++ and show how easy is to do cool effects with the games, in the last example he makes a kind of super loved by mobile gamers in Lua. In the first chapters he teaches how to install and the basics of the framework, he also gives examples of tools that he use and are recommended to create spitesheets, particles, bitmap fonts and sound effects. If you already know C++ or another Object Oriented programming language, I think that the examples will show you the framework in a way that you will not be scared by the code, but if you've never used C++ or another Object Oriented programming language... this can be hard, but if you read again the book become easy, the examples showed are clear, you will take it. All the effort will be worth on you first game done, when you play something that you've made is one of the best things, all you need to start is on the book learn by examples mix some techniques and practice more and more, as soon as you can imagine your games will be good to show to your friends and make some money. I liked that the examples are simple, the code is explained block by block, game features that you and your users appreciate are showed and the examples explain how to work with physics Box2D and Chipmunk, particles, primitive draws, touch, collision and much more. This book is totally recommended if you want to learn or if you want to take advantage of the framework to make professional games.
Amazon Verified review Amazon
Jaime Sierra May 15, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Hello everyone, I'm Chilean and this book (2nd Edition) I looked forward, I am programmer Cocos2D ObjC is good but is only for iOS, but Cocos2D-x can be programmed for iOS and Android, which is great advantage . I tried for months to learn Cocos2D-x from many web, but it was not clear to me now to the book "Cocos2d-x by Example: Beginner's Guide - Second Edition" is updated and a true guide to set up my computer, and to design in C ++ as well as several aspects that are familiar to cocos2D ObjC. There is an excellent support service from the same publisher, respond quickly and well detailed.In short, excellent book.
Amazon Verified review Amazon
Christian S. Jun 10, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The first version of this book was my second book I bought from Packt about 2 years ago. At that time I completed the book in a couple of months. Roger Engelbert did a splendid work in creating the examples and progressively increasing the difficulty to expose different concepts in each chapter. Considering how difficult it is to introduce C++ in an Objective-C and Java environment, they were carefully explained and easy to follow and the code just run as expected.This second edition does not disappoint. Besides updating all the libraries and frameworks to the most current versions (2 years in the mobile world is a lot!), the examples and explanations remain clear, carefully crafted.The mayor difference with the first edition is Chapter 10. It replaced the same chapter in the first edition (Eclipse setup in C++ for crossplatform builds) with the latest CocosIDE and Lua, which did not exist when the first version was released. This chapter feels like a cliffhanger waiting for a next book to show all the potential of Lua and the new CocosIDE.
Amazon Verified review Amazon
juan Oct 09, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
es muy bueno el libro
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