Cocos2d-x Tutorial for Beginners (2024)

Cocos2d-x Tutorial for Beginners (1)

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! :]

Note: This tutorial assumes you know the basics of C++ development. If you are new to C++, be sure to read a book on the subject first.

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.

Note: Cocos2D requires Python 2.7+ installed on your machine. If you aren’t sure what version of Python you have, type 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:

Cocos2d-x Tutorial for Beginners (2)

Note: Depending on which shell you use, you might see some different output. In the above screenshot, the setup package prompts for “source /Users/rwenderlich/bash_profile.” commands since I’m using Bash, but had I been using Zsh, for example, it would have prompted me to run “source /Users/rwenderlich/.zshrc”.

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.

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:

Cocos2d-x Tutorial for Beginners (3)

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:

Cocos2d-x Tutorial for Beginners (4)

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:

Cocos2d-x Tutorial for Beginners (5)

Notice the third argument you passed to createWithRect1.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:

Cocos2d-x Tutorial for Beginners (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:

// 1Size designSize = Size(480,320);Size resourceSize = Size(960,640);// 2director->setContentScaleFactor(resourceSize.height / designSize.height);director->getOpenGLView()->setDesignResolutionSize( designSize.width, designSize.height, ResolutionPolicy::FIXED_HEIGHT);

Here’s what the code above does:

  1. Here you define designSize – the size you’re using when creating your game logic – and resourceSize – the size on which all your art assets are based.
  2. 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:

Cocos2d-x Tutorial for Beginners (7)

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:

// 1if ( !Layer::init() ) { return false;}// 2auto origin = Director::getInstance()->getVisibleOrigin();auto winSize = Director::getInstance()->getVisibleSize();// 3auto 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:

  1. First you call the super class’s init method. Only if this succeeds do you proceed with HelloWorldScene‘s setup.
  2. You then get the window’s bounds using the game’s Director singleton.
  3. 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.
  4. 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! :]

Cocos2d-x Tutorial for Beginners (8)

Cocos2d-x Tutorial for Beginners (2024)

FAQs

Is Cocos2d good for game development? ›

Cocos2D is a comprehensive framework, open source and completely free. This is the main reason for it being the most used development platform, surpassing Marmalade or Unity which are not completely free. Unity3D has been and still remains the most used development platform to develop 3D games.

Is Cocos Creator worth it? ›

Cocos Creator is more than a efficient, lightweight, free, open-source, cross-platform graphics engine: it's also a platform to create 3D content in real time. It is not only flawless for 2D and 3D game development, it also provides integral solutions for automotive, XR, Metaverse and Education.

What coding language does Cocos2d use? ›

Cocos2d is an open-source game development framework for creating 2D games and other graphical software for iOS, Android, Windows, macOS, Linux, HarmonyOS, OpenHarmony and web platforms. It is written in C++ and provides bindings for various programming languages, including C++, C#, Lua, and JavaScript.

What is the difference between Cocos Creator and Cocos2d-x? ›

In Cocos2d-x, the development method is driven by code and most of the game's data is stored in the code, unless the developer has built his/her own data driven framework. In the framework of Cocos Creator, all the scenes will be serialized as pure data.

Is Cocos2d hard to learn? ›

Learning Curve

It's created for people who know C++ and know it well, so for people who aren't used to coding in C++, adaptation for getting started with a Cocos2d-x project requires more time than with Unity's GUI. Cocos Creator vs Unity fight is a bit different, though.

Is Python or C++ better for game development? ›

While faster than C++, Python is sufficient for games with basic graphics, gameplay, and AI requirements. Python simplifies development compared to lower-level languages, enabling faster iteration. Many game frameworks like Pygame and Panda3D use Python under the hood.

Is Cocos Creator easy? ›

With some familiarity and understanding with the editor, it is easy to get familiar with the Cocos Creator development process with simple examples: Hello world! Quick start: Making your first game.

How much does Cocos game engine cost? ›

Cocos Creator is free. Though the editor is not open-source, the engine is 100% open source.

What is the difference between Unity and cocos creator? ›

Unlike Unity, which supports CG, GLSL, and HLSL, Cocos Creator only supports GLSL as a shader programming language. The table below compares the file formats they use and the differences in DSL. Unity uses a custom shader file as the DSL, while Cocos creator uses Yaml as the DSL file format.

Is Cocos2d fast? ›

Fast performance.

Cocos2d-x offers excellent performance, especially for games with many objects and computations.

Can you use Python in Cocos2d? ›

Cocos2d is reliable and mature open source software framework that is used to build 2D games, apps and other cross-platform GUI-based interactive programs. It is written in Python using pyglet library. Cocos2d is one of the few Python game libraries, other than PyGame.

Can you use C++ in Cocos? ›

Cocos Creator supports JavaScript, built in. Edit your Scenes and source code all from within. However, If you are a C++ or Lua developer, Cocos Creator allows exporting of Scenes to sour code for further development.

What script language does Cocos creator use? ›

Cocos Creator supports both TypeScript and JavaScript programming languages.

What is the difference between Cocos2D-x and libGDX? ›

Both support the same targets. The main difference is, that cocos2d-x's main language is C++ and libGDX's is Java (some C and C++ components for performance dependent code). If you want to measure real world performance, you would need to run some standard benchmarks on both engines.

What platforms does Cocos Creator support? ›

Publish to Multiple Platforms
  • iOS.
  • Android.
  • Huawei HarmonyOS.
  • Open HarmonyOS.
  • Web Mobile - H5.
  • WeChat Mini Games.
  • Douyin Mini Games.
  • Facebook Instant Games.

Is Cocos game engine good? ›

the quality of engine (renderer, physics, etc) is awesome and I experienced more than 5 commercial projects. the cocos2d-x version is primly in c++ and It's so convenient to use. It also support scripting as well. recently It also added 3D feature which will make it more popular besides unity3d.

What IDE do most game developers use? ›

What IDE do most developers use? The most used IDE for Mac, Windows, and Linux is Visual Studio Code. It is one of the easiest ones to get into.

What is the best coding program for game development? ›

C++: C++ is an object-oriented programming language. Its speed, ease of use, and widespread adoption make it stand out as a highly desirable language. According to Game-Ace, it is widely considered the gold standard in game programming, and many call it the best coding language for games.

Top Articles
Latest Posts
Article information

Author: Tish Haag

Last Updated:

Views: 6057

Rating: 4.7 / 5 (47 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Tish Haag

Birthday: 1999-11-18

Address: 30256 Tara Expressway, Kutchburgh, VT 92892-0078

Phone: +4215847628708

Job: Internal Consulting Engineer

Hobby: Roller skating, Roller skating, Kayaking, Flying, Graffiti, Ghost hunting, scrapbook

Introduction: My name is Tish Haag, I am a excited, delightful, curious, beautiful, agreeable, enchanting, fancy person who loves writing and wants to share my knowledge and understanding with you.