Search icon
Cart icon
Close icon
You have no products in your basket yet
Arrow left icon
All Products
Best Sellers
New Releases
Learning Hub
Free Learning
Arrow right icon
Cocos2d Game Development Essentials
Cocos2d Game Development Essentials

Cocos2d Game Development Essentials: For new users - a quickstart guide to bringing your mobile game ideas to life with Cocos2D

$19.99 $13.98
Book Jan 2015 136 pages 1st Edition
$19.99 $13.98
$15.99 Monthly
$19.99 $13.98
$15.99 Monthly

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
Buy Now

Product Details

Publication date : Jan 23, 2015
Length 136 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781784390327
Category :
Table of content icon View table of contents Preview book icon Preview Book

Cocos2d Game Development Essentials

Chapter 1. Getting Started with Cocos2d

In this chapter, you will learn how to create your first Cocos2d project. You will make a simple game that could be extended to a full title if you choose. You will also learn how to deploy on Android using Apportable.

In this Chapter, we will cover the following topics:

  • Installing Cocos2d

  • Working of the Cocos2d app

  • Creating a project with the template

An introduction to Cocos2d

Cocos2d for iPhone is an open source framework to build cross-platform 2D games with Xcode and Objective-C. Cocos2d is licensed by Massachusetts Institute of Technology (MIT), meaning that in addition to being free to use, there is no need to open source your game, and no licensing or profit share fees to pay to use it in a commercial product.

Cocos2d can be compiled for iOS and Android using the tool Apportable, the official sponsor of the Cocos2d project. This framework encourages and allows you to be creative; its visual editor, SpriteBuilder, allows you to create and lay out scenes, design animations, and play around with physics and sprite sheets. Cocos2d is built on top of OpenGL ES 2.0, and the layer between the two has been highly optimized over a period of time. It also supports custom OpenGL shaders when you want to change the way your scene is rendered by OpenGL.

You might be wondering why you should use Cocos2d in the newly released Apple native library, SpriteKit, and I believe the answer is relatively simple. Cocos2d is a far more mature library than SpriteKit, and it has more features while still being easier to use. Cocos2d is also open source, which means you can add to it if needed, and see how it works behind the scenes. However, the real advantage of Cocos2d over SpriteKit is its cross-platform ability; Cocos2d can be cross-compiled to Android from Objective-C. This might sound like magic; I wouldn't be surprised if a bit of magic was involved, but it does work, and you will see it work in this book. Cocos2d is also fully compatible with Swift, Apple's new programming language, which was unveiled in June 2014. While Swift has created a considerable buzz, Objective-C will nevertheless be essential for anyone wishing to work with Cocos2d. If you are using Objective-C, another benefit is that Cocos2d supports iOS5+ unlike SpriteKit, which only supports iOS 7+.

Installing Cocos2d

Before you can do anything, you need to install Cocos2d. Let's get started.

There are several ways to install Cocos2d. Some methods are easy, whereas some are harder to get started, but it will make upgrading in the future much easier. Before you install Cocos2d, you need to ensure that you have the latest version of Xcode installed. Xcode can be found on the Mac App Store or on the Apple Developer Program portal. Additionally, to push your apps into an iOS device, you will need a paid iOS developers account. New accounts can be made at

Installing Cocos2d with the installer

Using the installer is the easiest method of installation and is recommended for first time users because it will install the relevant documentation and project templates automatically.

To install Cocos2d with the installer, follow these steps:

  1. Download the latest version of the installer from

  2. Open the installer and follow the prompts to install Cocos2d.

  3. Go to the Mac App Store and install SpriteBuilder; we will use this in later chapters.

Creating a Hello World project

You can start by creating a new project from the template that you just installed in Xcode. Open up Xcode and click New Project. You will see a new section in the templates for cocos2d v3.x. Click on this, and create a new project with the cocos2d iOS template, as shown in the following figure. You can now build and run the template, and have a play around with the example app:


Cocos2D-Swift Version 3 was a minor upgrade from Version 2. Its main features were an official support for Android, built-in physics engine, and a cleaned up API. As part of the API cleanup, many classes were either renamed or removed all together. This can make it difficult to follow tutorials from old versions.

Installation for Android

To build and run the Cocos2d app for Android, you need to install Apportable, a cross-compiler that will compile the Objective-C code to run on Android devices. This sounds crazy, but it actually works; you are about to try it for yourself.

You will also need to plug in an Android device and ensure that USB debugging is enabled. This step is different for every Android device, so if you are not sure how to do it, the best method is to go online and search for Enable USB debugging on <device name>.

The first step is to download and install Apportable, the instructions for which can be found at You will be asked to sign up to an account, but it is completely free to build Cocos2d games; you can even push your game to the Google Play Store. The steps on how to install your app in your Android phone are as follows:

  1. Once you have installed Apportable, open a terminal window and navigate to the Hello World project folder.

  2. From inside the project folder, run the command Apportable load.

  3. You will then be asked a series of questions. First, you will be asked whether your app is using OpenGL ES 1 or 2. Answer with 2. The difference between these options is that Cocos2d v3 is built on top of Open GL ES v2. They have a different API and so selecting the correct option is important.

  4. The next question will ask whether your app should initially launch in portrait or landscape. Obviously, this will change between projects, but for now, answer L for landscape.

  5. You will then see a large amount of terminal output while Apportable builds the project. Once the build is complete, Apportable will attempt to install your app in the Android device that is plugged into your computer.

Once the app is installed, it will automatically open. If your phone is locked, you will have to manually unlock it.

Template project code breakdown

Now that you have successfully built and deployed your first Cocos2d app, let's see how it actually works. In Xcode, open up IntroScene.m.


The IntroScene.m file corresponds with the first scene you see when you load up your app. We will go into more detail on scenes in the next chapter, but for now, all you need to know is what a scene looks like. The first part of the init() method is a slightly different method compared to the standard Objective-C init pattern.

  1. First, assign self, and then check to make sure that it did not return nil. This is a standard Objective-C pattern to guard against a sub-class or super class not initiating properly:

    // Apple recommend assigning self with supers return value
        self = [super init];
        if (!self) return(nil);
  2. Next, is your first piece of Cocos2d code:

    // Create a colored background (Dark Grey)
        CCNodeColor *background = [CCNodeColor nodeWithColor:[CCColor colorWithRed:0.2f green:0.2f blue:0.2f alpha:1.0f]];
        [self addChild:background];

    CCNodeColor is a Cocos2d object that allows you to create and display a rectangle of a single color.

  3. You create the color node by passing in the color that you want in Cocos2d; colors are represented by the CCColor class. For now, you are making a dark gray background, but experiment by changing the color values, and then building and running the app to see the effect.

  4. Once you have created the color node, you need to add it to the scene so that Cocos2d knows how to render it. Until you add it, it will not be visible on screen. You add the background child to self, which in this case is the intro scene.

  5. Now, you have a solid background color, but the app is still pretty boring. Let's add some text to say 'Hello World':

        // Hello World
        CCLabelTTF *label = [CCLabelTTF labelWithString:@"Hello World" fontName:@"Chalkduster" fontSize:36.0f];
        label.positionType = CCPositionTypeNormalized;
        label.color = [CCColor redColor];
        label.position = ccp(0.5f, 0.5f); // Middle of screen
        [self addChild:label];

CCLabelTTF is a label class that allows you to add text to your scene. Labels are created by passing in a string, a font name, and a font size, and then setting a position type. Position types will be covered in the next chapter as well, but a normalized position type allows you to position your node with a percentage from the left and bottom, rather than a fixed position. This is of great value when you are developing an app that will run on multiple screen sizes, such as Android phones and tablets. Set the label color to red and then set the position to (0.5, 0.5) using ccp, which is Cocos2d shorthand for making a new CGPoint array. Points in Cocos2d have an origin at the bottom-left of the scene. Remember that this is a percentage, so we are placing it 50 percent in and 50 percent up, which is the center of the screen. Once you have finished setting up your label, you add it to the scene so that it will be rendered.

Now you need a way to get to the next scene, where your game will have some interaction. You need to add a button:

    // Helloworld scene button
    CCButton *helloWorldButton = [CCButton buttonWithTitle:@"[ Start ]" fontName:@"Verdana-Bold" fontSize:18.0f];
    helloWorldButton.positionType = CCPositionTypeNormalized;
    helloWorldButton.position = ccp(0.5f, 0.35f);
    [helloWorldButton setTarget:self selector:@selector(onSpinningClicked:)];
    [self addChild:helloWorldButton];

CCButton is a button node that gives you a target and a selector for when the node is tapped on. You can also set a block to run on tap instead, but in this example, we are using the target / selector paradigm. You create the button in a similar way to the label with a string, font name, font size, and position. The difference now is that you also need to set the target and selector. You will need to set the target to self, and run a method that is in this class, which for this example is onSpinningClicked. Add this button to the scene to be rendered as well.

Let's have a look at the method that is called when you tap the button:

- (void)onSpinningClicked:(id)sender
    // start spinning scene with transition
    [[CCDirector sharedDirector] replaceScene:[HelloWorldScene scene]
                               withTransition:[CCTransition transitionPushWithDirection:CCTransitionDirectionLeft duration:1.0f]];

In this method, you are making a call to the CCDirector: the director of the game that manages the scene currently on the screen to replace the current scene with the HelloWorld scene. We will use a transition to do this, which will be covered fully later in this book. For now, we will start with a simple transition that will push the new scene that comes in from the left. You don't have to use a transition, but can add a nice bit of polish to your game.

The HelloWorldScene.m class

Let's take a look at the scene you have transitioned to. If you play around with the app you will see that you have an image that is rotating, and that starts in the center of the screen. When you tap the screen, it moves to where you tapped. Let's see how this works.

  1. Starting in the init method, the first part is always the same, but there is something new now:

        // Apple recommend assigning self with supers return value
        self = [super init];
        if (!self) return(nil);
        // Enable touch handling on scene node
        self.userInteractionEnabled = YES;

    Enabled user interaction tells the CCDirector class that you want the scene to receive touches. This is so that when you tap the screen, your image moves.

  2. Next, you create the background in the same way as in IntroScene.m. The following code is another new concept:

        // Add a sprite
        _sprite = [CCSprite spriteWithImageNamed:@"Icon-72.png"];
        _sprite.position  = ccp(self.contentSize.width/2,self.contentSize.height/2);
        [self addChild:_sprite];

    You are now creating the image that starts in the middle of the screen. These images are known as sprites, and they are created using their image names. Using the names makes Cocos2d look for an image in the app bundle, with the name you provide. You save the sprite reference in an instance variable, so it can be moved around the screen. Then, the position of the sprite is set to start in the center of the screen. Note that this is different to the position type that was used before; now you are setting it to a fixed coordinate rather than a percentage. Then, add the sprite to the scene to be rendered.


    The Cocos2d template stores its nodes in instance variables. Apple recommends against this practice, stating that the preferred method to store variables accessible within a class is through properties. Apple's recommended practice will be used in this book. More information can be found at

  3. Now, you will add an animation to your sprite in order to make it spin:

        // Animate sprite with action
        CCActionRotateBy* actionSpin = [CCActionRotateBy actionWithDuration:1.5f angle:360];
        [_sprite runAction:[CCActionRepeatForever actionWithAction:actionSpin]];

    This code creates a CCActionRotateBy action with a duration of 1.5 seconds and an angle of 360 degrees clockwise. This means that you want the sprite to rotate once by 360 degrees, and take 1.5 seconds to complete the rotation. You will notice that in the app, the rotation runs continuously; this is achieved on the next line with the relatively self-explanatory CCActionRepeatForever action. You then run the action on your sprite in order to start the rotation. There are many different types of CCAction that will be covered in this book; we have only just touched the surface of what is possible with this example:

    // Create a back button
        CCButton *backButton = [CCButton buttonWithTitle:@"[ Menu ]" fontName:@"Verdana-Bold" fontSize:18.0f];
        backButton.positionType = CCPositionTypeNormalized;
        backButton.position = ccp(0.85f, 0.95f); // Top Right of screen
        [backButton setTarget:self selector:@selector(onBackClicked:)];
        [self addChild:bcackButton];
  4. Next, you create a button that will take you back to the main menu. This works exactly the same as in the previous scene.

  5. Now, let's look at how you handle touch. Scroll down to the code and find the touchBegan method.


    In Xcode, you can use Ctrl+6 and start typing the method you are looking for. This is a quick way to navigate code.

    -(void) touchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
        CGPoint touchLoc = [touch locationInNode:self];
        // Log touch location
        CCLOG(@"Move sprite to @ %@",NSStringFromCGPoint(touchLoc));
        // Move our sprite to touch location
        CCActionMoveTo *actionMove = [CCActionMoveTo actionWithDuration:1.0f position:touchLoc];
        [_sprite runAction:actionMove];

How does touchBegan work? It gets activated when you first touch the screen, and you get a location of touch translated into the coordinate space of your node. This is an important step because UIKit (the framework used by iOS) uses a different coordinate space to Cocos2d and OpenGL. If the location doesn't get translated, you would end up moving your node to the wrong position on the screen.


It is important to note the difference between touchBegan and touchEnded. Choosing the correct one depends on what you are trying to achieve with your UI. If you want an action to occur as soon as the user touches the screen, then use touchBegan. If you want an action to occur when the user lifts their finger, then use touchEnded.

The template then logs the position that you are moving the sprite to, using a CCLog – a macro helper that allows you to disable logging in release builds.

Next, you will create a CCActionMoveTo action. This action is similar to CCActionRotateBy, but now you are moving a node to an identified position rather than rotating a node by an angle. You want your sprite to move to the touch position, using the touch location that was translated. For this example, you want the move to take 1 second, but feel free to change the duration and rebuild to see the effects. Once you have created the action, run it on the sprite. Note that you are using the instance variable that was created in the init method.


Congratulations! You have built your first cross-platform app and stepped through the code to see how it works. At this point, you should have a basic idea of how a Cocos2d app is put together. You have created scenes to contain different screens of your game, and you have used the CCDirector class to move between them. You have created different types of nodes to display content on the screen, including CCLabelTTF for text content, CCButton to create a button on screen, and CCSprite to display an image. You have used CCActions in the form of CCActionRotateBy and CCActionMoveTo, and you modified their behavior using CCActionRepeatForever. You also learned how to create a solid rectangle of color using CCNodeColor.

You should now have a play with the sample code and see what you can do. Try changing the durations and text, and the colors of the background. You could also try to replace the image with your own or have more than one image.

In the next chapter, you will build on the knowledge gained in this chapter by going over the details of nodes, sprites and scenes. You will also build your very first game and deploy it to your device.

Left arrow icon Right arrow icon

Key benefits

What you will learn

Use sprites and nodes to create scenes to form the foundation of your game Discover how SpriteBuilder and its graphical tools can be used to develop your game and increase its complexity Design professional, impressive, and funfilled animations Create an impressive user interface for an engaging gaming experience Explore and use physics engines for attractive gameplay and use them to add a professional finish to your game Add physics to your game for a more realistic experience Accept user input through a variety of methods including touch and accelerometer

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
Buy Now

Product Details

Publication date : Jan 23, 2015
Length 136 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781784390327
Category :

Table of Contents

13 Chapters
Cocos2D Game Development Essentials Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
1. Getting Started with Cocos2d Chevron down icon Chevron up icon
2. Nodes, Sprites, and Scenes Chevron down icon Chevron up icon
3. SpriteBuilder Chevron down icon Chevron up icon
4. Animation with SpriteBuilder Chevron down icon Chevron up icon
5. User Interaction and Interface Chevron down icon Chevron up icon
6. Physics Engines Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by

No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial


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 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
  • To contact us directly if a problem is not resolved, use
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.