Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
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
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

$15.99 per month
Book Jan 2015 136 pages 1st Edition
eBook
$19.99 $13.98
Print
$32.99
Subscription
$15.99 Monthly
eBook
$19.99 $13.98
Print
$32.99
Subscription
$15.99 Monthly

What do you get with a Packt Subscription?

Free for first 7 days. $15.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

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 http://developer.apple.com/ios.

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 http://www.cocos2d-swift.org/download

  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:

Tip

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 https://www.Apportable.com. 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.

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.

    Tip

    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 https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html.

  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.

    Note

    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.

Tip

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.

Summary


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

Product Details

Country selected

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

What do you get with a Packt Subscription?

Free for first 7 days. $15.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details


Publication date : 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
www.PacktPub.com 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

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%
Top Reviews
No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.