Cocos2d-x Tutorial for Beginners
In this Cocos2d-x tutorial, learn how to create a basic cross-platform game for iOS, Android, and more using C++! By Guanghui Qu.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Cocos2d-x Tutorial for Beginners
30 mins
Cocos2d-x is a fast, powerful, and easy-to-use open source 2D game engine.
It’s is very similar to Apple’s Sprite Kit, but has one key advantage – Cocos2d-x is cross platform.
This means with one set of code, you can make games for iOS, Android, Windows Phone, Mac OS X, Windows Desktop and Linux. This is huge for indie game devs!
In this tutorial, you will learn how to create a simple 2D game in Cocos2d-x with C++. And yes — there will be ninjas! :]
Getting Started
Download the latest version of Cocos2d-x at www.cocos2d-x.org/download; this tutorial used version 3.5.
Place the downloaded file wheres you’d like to store your Cocos2d-x installation, such as in your home directory, then unzip it.
Open Terminal and cd into the folder you just extracted. For example, if you placed the project in your home directory, run the following command:
cd ~/cocos2d-x-3.5/
Now run the following command:
python setup.py
This sets up the necessary shell environment variables. When it prompts you to configure the Android-specific variables NDK_ROOT
, ANDROID_SDK_ROOT
and ANT_ROOT
, just press Enter three times to finish the configuration.
python
on the command line and it will display the version (then hit Ctrl-D to exit). If you have an older version of Python, install the latest version of Python at python.org.As you can see in the following screenshot, the script instructs you to execute another command to complete the setup:
Enter the command as the script’s output instructed. A great timesaving tip: you can use a tilde (~) in place of /Users/your_user_name, so to save keystrokes you could type the following:
source ~/.zshrc (or source ~/.bash_profile)
The command you entered simply re-processes your shell configuration and gives it access to the new variables. Now you can call the cocos command in Terminal from any directory.
Run the following command to create a C++ game template named SimpleGame:
cocos new -l cpp -d ~/Cocos2d-x-Tutorial SimpleGame
This creates a directory named Cocos2d-x-Tutorial in your home directory, and inside that, a sub-directory named SimpleGame that contains your project’s files.
Note: To learn about the available cocos subcommands, type cocos --help or cocos -h. You can also learn about any subcommand’s options by appending “--help” or “-h”, such as cocos new -h to see the options for the new command.
Note: To learn about the available cocos subcommands, type cocos --help or cocos -h. You can also learn about any subcommand’s options by appending “--help” or “-h”, such as cocos new -h to see the options for the new command.
Double-click ~/Cocos2d-x-Tutorial/SimpleGame/proj.ios_mac/SimpleGame.xcodeproj in Finder to open the project in Xcode.
Once you’re Inside Xcode, ensure that SimpleGame Mac is the active scheme, as shown below:
While Cocos2d-x is capable of building games for many platforms, in this tutorial you’ll focus on making an OS X app. Porting this project to other platforms is a trivial (yes, trivial!) matter discussed briefly at the end of this tutorial.
Build and run your app to see the template project in all its glory:
Resolution Setup
By default, Cocos2d-x games are named “MyGame” and have a resolution of 960×640, but those details are easy to change.
Open AppDelegate.cpp and find the following line inside AppDelegate::applicationDidFinishLaunching
:
glview = GLViewImpl::create("My Game");
Replace that line with the following code:
glview = GLViewImpl::createWithRect("SimpleGame", Rect(0,0, 480, 320), 1.0);
This changes the app’s name to “SimpleGame” and sets its resolution to 480×320 to match the background art included with the template.
Build and run your app again to see your new, smaller game:
Notice the third argument you passed to createWithRect
— 1.0
. This parameter scales the frame, which is usually \used for testing resolutions larger than your monitor. For example, to test a 1920×1080 resolution on a monitor smaller than 1920×1080, you could pass 0.5
to scale the window to 960×540.
While this call to createWithRect
changes the game’s frame on desktops, it doesn’t work this way on iOS devices; instead, the game’s resolution matches the screen size. Here is how it looks on an iPhone 6:
So how do you handle multiple resolutions? In this tutorial, you’ll create a single set of game resources based on a 960×640 resolution, then simply scale the assets up or down as necessary at runtime.
To implement this, add the following code inside AppDelegate::applicationDidFinishLaunching
, just above the line that calls setDisplayStats
on director
:
// 1
Size designSize = Size(480,320);
Size resourceSize = Size(960,640);
// 2
director->setContentScaleFactor(resourceSize.height / designSize.height);
director->getOpenGLView()->setDesignResolutionSize(
designSize.width, designSize.height, ResolutionPolicy::FIXED_HEIGHT);
Here’s what the code above does:
- Here you define
designSize
– the size you’re using when creating your game logic – andresourceSize
– the size on which all your art assets are based. - These lines tell your game’s
Director
to scale the assets as necessary based on the design and resource sizes you provided.
For a detailed explanation of how Cocos2d-x handles resolutions, please refer to the Cocos2d-x wiki entry on Multi-resolution adaptation.
Adding a Sprite
Next, download the resources file for this project and unzip it to a convenient location.
Select all the files in the SimpleGameResources folder you just extracted and drag them into the Resources group in your Xcode project. In the dialog that appears, be sure to check Copy items if needed, SimpleGame iOS and SimpleGame Mac before clicking Finish:
Next open HelloWorldScene.h add the following line just after the line that includes cocos2d.h:
using namespace cocos2d;
This specifies you’ll be using the cocos2d
namespace; this lets you do things like write Sprite*
instead of cocos2d::Sprite*
. It’s not absolutely necessary, but it certainly makes development more pleasant. :]
Now you’ll need a private member variable to point to your player sprite. Add the following code to the HelloWorld
declaration:
private:
Sprite* _player;
Next, open HelloWorldScene.cpp and replace the contents of the HelloWorld::init method with the following:
// 1
if ( !Layer::init() ) {
return false;
}
// 2
auto origin = Director::getInstance()->getVisibleOrigin();
auto winSize = Director::getInstance()->getVisibleSize();
// 3
auto background = DrawNode::create();
background->drawSolidRect(origin, winSize, Color4F(0.6,0.6,0.6,1.0));
this->addChild(background);
// 4
_player = Sprite::create("player.png");
_player->setPosition(Vec2(winSize.width * 0.1, winSize.height * 0.5));
this->addChild(_player);
return true;
Here’s the play-by-play of this method:
- First you call the super class’s
init
method. Only if this succeeds do you proceed withHelloWorldScene
‘s setup. - You then get the window’s bounds using the game’s
Director
singleton. - You then create a
DrawNode
to draw a gray rectangle that fills the screen and add it to the scene. This serves as your game’s background. - Finally, you create the player sprite by passing in the image’s name. You position it 10% from the left edge of the screen, centered vertically, and add it to the scene.
Build and run your app; voila, ladies and gentlemen, the ninja has entered the building! :]