Home Game Development Cocos2d Game Development Essentials

Cocos2d Game Development Essentials

books-svg-icon Book
eBook $19.99 $13.98
Print $32.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $19.99 $13.98
Print $32.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
About this book
Publication date:
January 2015
Publisher
Packt
Pages
136
ISBN
9781784390327

 

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.

Cocos2d Game Development Essentials
Unlock this book and the full library FREE for 7 days
Start now