Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Cocos2dx

Learn Cocos2dx - 10 Code Examples & CST Typing Practice Test

Cocos2d-x is a cross-platform, open-source C++ game engine optimized for 2D games, offering high performance, a lightweight architecture, scene graph system, physics, animations, particle effects, and deployment to mobile, desktop, web, and consoles.

View all 10 Cocos2dx code examples →
Cocos2d-x Simple Counter GameCocos2d-x Basic Hello World SceneCocos2d-x Touch Move SpriteCocos2d-x Sprite Movement with ActionsCocos2d-x Keyboard Input MovementCocos2d-x UI Button ExampleCocos2d-x Particle Effect ExampleCocos2d-x Background MusicCocos2d-x Sprite Animation ExampleCocos2d-x Scene Transition Fade

Learn COCOS2DX with Real Code Examples

Updated Nov 24, 2025

Explain

Cocos2d-x uses C++ as its core programming language with optional JavaScript/Lua bindings.

It provides a scene graph, sprite system, actions, transitions, physics, UI widgets, audio, and efficient rendering pipelines.

Cocos2d-x powers countless 2D mobile games, educational apps, casual titles, animation apps, and high-performance 2D experiences on Android, iOS, and desktop.

Core Features

Scene management

Sprite system

Actions (move, rotate, scale, fade)

Particle system

UI widgets via Cocos UI

Basic Concepts Overview

Director: manages game loop

Scene: main container

Layer: UI/logic layer

Node: base class for visual objects

Action: animations applied to nodes

Project Structure

Classes/ - C++ source files

Resources/ - images, audio, fonts

proj.android - Android config

proj.ios_mac - iOS/macOS config

CMakeLists.txt - build configuration

Building Workflow

Create scene and layers

Add sprites and nodes

Apply actions and animations

Integrate physics/UI/audio

Compile for mobile/desktop

Difficulty Use Cases

Beginner: simple sprite movement

Intermediate: 2D platformers

Advanced: physics games, complex UI

Expert: optimizing FPS-heavy scenes

Enterprise: educational/game portals

Comparisons

Cocos2d-x vs Unity: lightweight 2D vs full 3D engine

Cocos2d-x vs Godot: C++ performance vs editor-driven workflow

Cocos2d-x vs Cocos Creator: C++ native vs JS editor-based

Cocos2d-x vs LibGDX: C++ vs Java approach

Cocos2d-x vs Phaser: mobile native vs browser-first

Versioning Timeline

2010 - Cocos2d-x release

2013 - Major API rewrite for v3

2015 - JS/Lua bindings added

2018 - 3D features experiment

2025 - Stable lightweight 2D engine focus

Glossary

Scene Graph: hierarchical rendering model

SpriteSheet: combined image atlas

Action: transform over time

BMFont: bitmap font format

TMX: tilemap format

Installation Setup

Install Cocos2d-x from official GitHub

Install CMake + Python

Run setup.py to configure environment

Create a new project using cocos new

Open project in Xcode/Android Studio/VS

Environment Setup

Install Cocos2d-x

Install CMake + Python

Install Android NDK/SDK

Install Xcode

Configure VS or CLion

Config Files

CMakeLists.txt

AndroidManifest.xml

app-build.gradle

project.json (JS/Lua)

Resource config files

Cli Commands

cocos new MyGame -l cpp

cocos compile -p android

cocos run -p ios

cocos deploy

cocos gen-libs

Internationalization

Multi-language string tables

Unicode font support

Locale-based assets

Dynamic language switching

Formatted text rendering

Accessibility

Scaling for resolutions

Readable fonts

Colorblind-aware palettes

Localization-friendly UI

Touch event tuning

Ui Styling

Cocos UI widgets

Bitmap fonts

Sprite-based buttons

Scale9 sprites

Custom UI themes

State Management

Custom C++ classes

Scene variables

Singleton managers

Event listeners

Persistent storage

Data Management

JSON/XML

TMX maps

SQLite

Local file systems

Network sync

Architecture

Director -> global manager controlling scenes

Scene -> top-level game container

Layer -> grouping of visual elements

Sprite -> renderable image object

Action -> timed animation applied to nodes

Rendering Model

Batch rendering

Sprite-based rendering

OpenGL pipeline

Texture atlases

Node-based draw order

Architectural Patterns

Scene graph structure

Node-action architecture

Event-driven input

Physics-object interaction

UI widget tree

Real World Architectures

Mobile hypercasual engines

2D educational platforms

Casino slot machines

Match-3 engines

Puzzle game engines

Design Principles

Lightweight by design

C++ native speed

Focus on 2D excellence

Portable across platforms

Minimal runtime overhead

Scalability Guide

Batch sprites for efficiency

Use texture atlases

Pool reusable nodes

Lower physics iterations

Reduce particle counts

Migration Guide

Migrate from older API versions

Switch to CMake from old build

Update deprecated actions

Fix Android NDK path issues

Adjust to new scene/layer APIs

Performance Notes

Use sprite sheets with TexturePacker

Reduce draw calls with batching

Limit real-time physics complexity

Optimize update loops

Remove unused nodes quickly

Security Notes

Use secure storage for sensitive data

Avoid exposing game logic in JS/Lua

Validate server API calls

Use HTTPS for transactions

Encrypt local save files if needed

Monitoring Analytics

Custom FPS counters

Firebase/GA analytics

Crashlytics integration

In-house telemetry

Performance logging

Code Quality

Use RAII for memory safety

Organize scenes/modular classes

Avoid large update loops

Encapsulate logic cleanly

Use namespaces

Practical Examples

Endless runner

Match-3 puzzle game

Physics-based slingshot game

Casino/slots game

2D platformer with tilemap

Troubleshooting

Fix header include path errors

Fix Android NDK mismatches

Resolve missing resources

Check Action timing issues

Fix memory leaks in C++

Testing Guide

Test FPS and memory usage

Use debug draw for physics

Test on real mobile devices

Simulate resolution changes

Use unit tests for C++

Deployment Options

Android

iOS

Windows

macOS

Web (via JS bindings)

Tools Ecosystem

Cocos Creator (editor for JS)

Cocos Studio (deprecated)

TexturePacker for spritesheets

Spine & DragonBones animation

Box2D/Chipmunk physics engines

Integrations

Spine animations

AdMob ads

Firebase SDK

REST APIs

Analytics tools

Productivity Tips

Use spritesheets always

Prefer Actions over manual updates

Use debug draw for collision tuning

Keep draw calls minimal

Use CMake presets

Challenges

Create an endless runner

Build a tilemap-based level

Implement physics collisions

Create custom particles

Publish APK/IPA

Learning Path

Learn C++ basics

Understand nodes/scenes/actions

Add physics and UI

Build for Android/iOS

Optimize and publish

Skill Improvement Plan

Week 1: Nodes, scenes, actions

Week 2: Physics + collisions

Week 3: UI + audio systems

Week 4: Export Android/iOS builds

Week 5: Monetization + analytics

Interview Questions

Explain the Scene-Director architecture.

What are Actions and how do they work?

Difference between Sprite and Node?

How does memory management work?

How do you optimize draw calls?

Cheat Sheet

Scene = top container

Layer = logic/UI section

Node = base element

Action = animation tool

Director = main controller

Books

Cocos2d-x by Example

Cocos2d-x Game Development Essentials

Cocos2d-x Cookbook

Cocos2d-x Beginner’s Guide

Mobile Game Development with Cocos2d-x

Tutorials

Cocos2d-x official docs

Cocos YouTube tutorials

Udemy Cocos2d-x courses

Ray Wenderlich Cocos2d-x guides

Chinese dev tutorial sites

Official Docs

https://docs.cocos.com

https://cocos2d-x.org

https://github.com/cocos2d/cocos2d-x

Community Links

Cocos forums

GitHub

StackOverflow

Discord communities

Cocos WeChat groups

Community Support

Cocos2d-x Forum

GitHub discussions

StackOverflow

Cocos Discord

Cocos China dev communities

Monetization

AdMob integration

In-app purchases

Subscription systems

Rewarded video ads

Casino monetization models

Future Roadmap

More stable 2D tooling

Better JS/Lua bindings

Improved asset workflows

Modern C++ standard adoption

Better Android build pipeline

When Not To Use

3D-heavy games

AAA production games

Complex UI-based apps

Beginner-friendly visual editing

Projects needing rapid prototyping

Final Summary

Cocos2d-x is a lightweight, high-performance C++ engine ideal for 2D mobile games.

Uses scene graph, sprites, physics, and actions to build rich 2D gameplay.

Highly popular in Asia's mobile gaming industry.

Cross-platform and open-source with tiny runtime footprint.

Best for developers wanting full control, performance, and native execution.

Faq

Is Cocos2d-x free?

Yes - MIT licensed.

Does it support Android/iOS?

Yes - highly optimized for both.

Is Cocos2d-x still maintained?

Yes - especially in mobile markets.

Is it good for 3D?

No - mostly 2D with limited 3D.

Is it beginner friendly?

Somewhat - requires C++ knowledge.

Code Sample Descriptions

1

Cocos2d-x Simple Counter Game

#include "CounterScene.h"
#include "ui/CocosGUI.h"

USING_NS_CC;

Scene* CounterScene::createScene() {
    auto scene = Scene::create();
    auto layer = CounterScene::create();
    scene->addChild(layer);
    return scene;
}

bool CounterScene::init() {
    if (!Layer::init()) return false;

    count = 0;
    label = Label::createWithTTF("Count: 0", "fonts/Marker Felt.ttf", 24);
    label->setPosition(Vec2(200, 200));
    this->addChild(label);

    auto incButton = ui::Button::create();
    incButton->setTitleText("+");
    incButton->setPosition(Vec2(150, 100));
    incButton->addClickEventListener([&](Ref*) { updateCount(1); });
    this->addChild(incButton);

    auto decButton = ui::Button::create();
    decButton->setTitleText("-");
    decButton->setPosition(Vec2(250, 100));
    decButton->addClickEventListener([&](Ref*) { updateCount(-1); });
    this->addChild(decButton);

    return true;
}

void CounterScene::updateCount(int delta) {
    count += delta;
    label->setString("Count: " + std::to_string(count));
}

A basic Cocos2d-x example that creates a counter label and buttons to increment or decrement the value.

Let’s Try →
2

Cocos2d-x Basic Hello World Scene

#include "HelloScene.h"
#include "cocos2d.h"

USING_NS_CC;

Scene* HelloScene::createScene() {
    auto scene = Scene::create();
    auto layer = HelloScene::create();
    scene->addChild(layer);
    return scene;
}

bool HelloScene::init() {
    if (!Layer::init()) return false;

    auto label = Label::createWithSystemFont("Hello, Cocos2d-x!", "Arial", 28);
    label->setPosition(Director::getInstance()->getVisibleSize() / 2);
    this->addChild(label);

    return true;
}

A classic Hello World label centered on the screen.

Let’s Try →
3

Cocos2d-x Touch Move Sprite

#include "TouchMoveScene.h"
#include "cocos2d.h"

USING_NS_CC;

Scene* TouchMoveScene::createScene() {
    auto scene = TouchMoveScene::create();
    return scene;
}

bool TouchMoveScene::init() {
    if (!Scene::init()) return false;

    sprite = Sprite::create("player.png");
    sprite->setPosition(Vec2(200, 150));
    addChild(sprite);

    auto listener = EventListenerTouchOneByOne::create();
    listener->onTouchBegan = [&](Touch* t, Event*) {
        sprite->setPosition(t->getLocation());
        return true;
    };
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

    return true;
}

Moves a sprite to where the user touches the screen.

Let’s Try →
4

Cocos2d-x Sprite Movement with Actions

#include "MoveActionScene.h"
#include "cocos2d.h"

USING_NS_CC;

bool MoveActionScene::init() {
    if (!Scene::init()) return false;

    auto sprite = Sprite::create("ship.png");
    sprite->setPosition(Vec2(100, 150));
    addChild(sprite);

    auto move = MoveBy::create(2.0f, Vec2(200, 0));
    sprite->runAction(move);

    return true;
}

Moves a sprite to the right using MoveBy action.

Let’s Try →
5

Cocos2d-x Keyboard Input Movement

#include "KeyboardScene.h"
#include "cocos2d.h"

USING_NS_CC;

bool KeyboardScene::init() {
    if (!Scene::init()) return false;

    sprite = Sprite::create("hero.png");
    sprite->setPosition(Vec2(200, 200));
    addChild(sprite);

    auto listener = EventListenerKeyboard::create();
    listener->onKeyPressed = [&](EventKeyboard::KeyCode key, Event*) {
        if (key == EventKeyboard::KeyCode::KEY_RIGHT_ARROW) sprite->setPositionX(sprite->getPositionX() + 10);
        if (key == EventKeyboard::KeyCode::KEY_LEFT_ARROW) sprite->setPositionX(sprite->getPositionX() - 10);
    };
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

    return true;
}

Moves a sprite with arrow keys.

Let’s Try →
6

Cocos2d-x UI Button Example

#include "UIButtonScene.h"
#include "ui/CocosGUI.h"

USING_NS_CC;

bool UIButtonScene::init() {
    if (!Scene::init()) return false;

    auto button = ui::Button::create();
    button->setTitleText("Click Me");
    button->setPosition(Vec2(200, 200));
    button->addClickEventListener([](Ref*) {
        CCLOG("Button clicked");
    });
    addChild(button);

    return true;
}

Adds a UI button that logs a message when clicked.

Let’s Try →
7

Cocos2d-x Particle Effect Example

#include "ParticleScene.h"
#include "cocos2d.h"

USING_NS_CC;

bool ParticleScene::init() {
    if (!Scene::init()) return false;

    auto particle = ParticleFireworks::create();
    particle->setPosition(Vec2(200, 200));
    addChild(particle);

    return true;
}

Displays a built-in particle system.

Let’s Try →
8

Cocos2d-x Background Music

#include "AudioScene.h"
#include "audio/include/AudioEngine.h"

USING_NS_CC;
using namespace experimental;

bool AudioScene::init() {
    if (!Scene::init()) return false;

    AudioEngine::play2d("music.mp3", true);
    return true;
}

Plays looping background music.

Let’s Try →
9

Cocos2d-x Sprite Animation Example

#include "AnimScene.h"
#include "cocos2d.h"

USING_NS_CC;

bool AnimScene::init() {
    if (!Scene::init()) return false;

    Vector<SpriteFrame*> frames;
    frames.pushBack(SpriteFrameCache::getInstance()->getSpriteFrameByName("walk1.png"));
    frames.pushBack(SpriteFrameCache::getInstance()->getSpriteFrameByName("walk2.png"));

    auto sprite = Sprite::createWithSpriteFrame(frames.at(0));
    sprite->setPosition(Vec2(200, 200));
    addChild(sprite);

    auto anim = Animation::createWithSpriteFrames(frames, 0.15f);
    sprite->runAction(RepeatForever::create(Animate::create(anim)));

    return true;
}

Creates a walking animation using sprite frames.

Let’s Try →
10

Cocos2d-x Scene Transition Fade

#include "StartScene.h"
#include "NextScene.h"
#include "ui/CocosGUI.h"

USING_NS_CC;

bool StartScene::init() {
    if (!Scene::init()) return false;

    auto button = ui::Button::create();
    button->setTitleText("Next Scene");
    button->setPosition(Vec2(200, 200));
    button->addClickEventListener([](Ref*) {
        Director::getInstance()->replaceScene(TransitionFade::create(1.0f, NextScene::createScene()));
    });
    addChild(button);

    return true;
}

Transitions to another scene using fade effect.

Let’s Try →

Frequently Asked Questions about Cocos2dx

What is Cocos2dx?

Cocos2d-x is a cross-platform, open-source C++ game engine optimized for 2D games, offering high performance, a lightweight architecture, scene graph system, physics, animations, particle effects, and deployment to mobile, desktop, web, and consoles.

What are the primary use cases for Cocos2dx?

2D mobile games. Casual/hypercasual games. Educational games/apps. Lightweight 2D engines for indie developers. Cross-platform 2D desktop or mobile publishing

What are the strengths of Cocos2dx?

Extremely lightweight and fast. Native performance with C++. Huge mobile game track record. Cross-platform with small runtime footprint. Ideal for 2D animations and sprite-heavy games

What are the limitations of Cocos2dx?

Not suited for 3D or complex console games. Steep C++ learning curve for beginners. UI editor ecosystem is weaker than Unity. Fewer modern engine tools. Maintenance requires manual project configuration

How can I practice Cocos2dx typing speed?

CodeSpeedTest offers 10+ real Cocos2dx code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.