Cocos2d-x / Cocos Creator Deep Engineering Guide
Cocos2d is a family of open-source game frameworks for 2D (and now 3D in Creator) with strong mobile focus. Cocos2d-x is the C++ core; Cocos Creator is the full editor + scene system built on top. This guide focuses on Cocos Creator 3.x (which uses Cocos2d-x under the hood).
1. Engine Architecture
Cocos Creator 3.x
Application
Scene -> Node tree
Component (Script, Render, Audio, UI, Physics...)
Scheduler (main loop): tick() -> update() -> lateUpdate()
Director: scene management, frame pacing
- Director is the central controller;
director.mainLoop() runs the frame.
- Nodes are the tree; Components (scripts) attach behavior.
- Scheduler: manages
update(), lateUpdate(), physicsUpdate() with priorities.
1.1 Update Order
fixedUpdate() // physics substeps (if using Box2D)
update() // gameplay logic per frame
lateUpdate() // camera, UI follow
render() // GPU submit
Rules:
- Node movement in physics:
move() or set RigidBody3D.velocity in fixedUpdate.
- Visual interpolation:
node.setPosition(lerp(...)) in update().
2. The Node-Component Model
import { Component, _decorator } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('Player')
export class Player extends Component {
@property speed: number = 10;
update(deltaTime: number) {
// movement, animation, input
}
onCollisionEnter(other: Collider) {
// physics callback
}
}
2.1 Pattern: Event-Driven
// Emit
this.node.emit('damage', amount);
// Listen
this.node.on('damage', this.onDamage, this);
node.on(): listen on the same node or bubble up.
targetOff(): remove all listeners on cleanup.
- Use typed events where possible (Cocos Creator 3.x supports
EventTarget).
2.2 Prefab Instantiation
import { instantiate, Prefab, resources } from 'cc';
const bullet = instantiate(this.bulletPrefab);
bullet.setPosition(this.node.worldPosition);
director.getScene().addChild(bullet);
Rule: cache prefab references via @property(Prefab), never load per frame.
3. Rendering
3.1 Pipeline Backends
| Platform |
Renderer |
| Desktop/Mobile (GL) |
OpenGL ES 3.1+ |
| iOS / Metal devices |
Metal |
| Android Vulkan |
Vulkan (via Cocos 3.x) |
| Web |
WebGL 2.0 |
3.2 Draw Calls & Batching
Sprite with the same texture/atlas: automatically batched by SpriteBatch/RenderBatch.
- Use texture atlases (
TexturePacker) aggressively.
- UI:
UIOpacity only on dynamic nodes; static UI should be grouped under a single Opacity parent.
3.3 Custom Rendering (Cocos Creator 3.x)
@ccclass('CustomEffect')
export class CustomEffect extends RenderableComponent {
getRenderPipeline() { return 'Builtin'; }
// use this.getMaterial(0) to change uniforms
}
RenderPipeline (Forward, Deferred) set in Project Settings.
- 2D games use Forward renderer; 3D can opt Deferred.
4. Physics
- Cocos Creator 3.x uses Bullet (3D) / Box2D (2D) via
physics-3d / physics-2d.
- Nodes:
Collider2D/Collider3D + RigidBody2D/RigidBody3D.
- Contact callbacks:
onBeginContact, onEndContact.
- Layers:
physicsGroup in Project Settings.
4.1 Character Controller
const controller = this.node.getComponent(CharacterController);
controller.move(dir, deltaTime);
- For platformers:
RigidBody2D + BoxCollider2D, manual velocity control.
- For 3D:
CharacterController3D from cc (or use Box2D bullet).
5. Audio
AudioSource component: play(), stop(), volume, loop.
- Audio files: MP3 (loop), OGG (streaming), WAV (small SFX).
- Preload audio on scene load; never load audio per event.
6. UI (UI Toolkit equivalent: Cocos UI)
- Nodes:
Sprite, Label, Button, Slider, ScrollView, RichText.
- Layout:
Layout component (horizontal/vertical/grid).
- Anchor points:
[0-1, 0-1] (unlike Unity's pivot).
Canvas node as root of UI tree; camera renders to UI layer.
Widget component for responsive layout (attach to parent edges).
7. Scripting Languages
| Option |
Use |
| TypeScript |
Primary, first-class support in Cocos Creator |
| C++ (Cocos2d-x) |
Engine extensions, GDExtension-like via bindings |
| Lua |
Legacy Cocos2d-x; not primary in Creator 3.x |
7.1 TypeScript Rules
- Use
@property decorators to expose fields.
- Typed node references:
@property(Node) target: Node;.
this.node: current node; this.node.parent: tree up.
director.loadScene('sceneName') to switch scenes.
8. Multiplayer
- Cocos Creator has no built-in high-level netcode; use:
- WebSocket/HTTP for REST APIs.
- Native TCP/UDP via C++ bindings for real-time.
- Socket.IO plugin for event-based messaging.
- Rollback/interpolation implemented in user code; see
skills/game/multiplayer-netcode/SKILL.md.
9. Asset Pipeline & Build
- Assets/:
.ts scripts, .prefab, .scene, .texture, .anim.
- Resource Manager (
resources.load()): load by path within resources/ folder.
AssetManager for runtime loading, scene loading.
- Build: Editor -> Build -> platform (iOS/Android/Web/Desktop) -> compile (Xcode/Gradle/Webpack).
- Remote asset bundle:
AssetManager.loadBundle from CDN for hot updates.
10. Performance Rules
- Profile: Cocos DevTools, Performance Monitor,
console.time().
- Node count: keep <5000 active; use culling (
NodePool or visibility checks).
- Object pool:
NodePool for bullets/enemies; never instantiate/destroy per event.
destroy() is deferred; removeFromParent() + pool recycling is faster.
- Light count: keep 3D dynamic lights < 4 on mobile.
- Audio: limit simultaneous audio sources (3-5 on mobile).
- Memory: release unused
AssetManager bundles explicitly.
10.1 Frame Budget (Mobile @ 30fps = 33ms)
| System |
Budget |
| Gameplay |
8ms |
| Physics |
5ms |
| Render (CPU) |
8ms |
| Audio |
2ms |
| GC / misc |
5ms |
| GPU |
16.6ms (GPU-bound, overlap CPU) |
11. Anti-Patterns
| Anti-pattern |
Consequence |
Fix |
| Instantiate/destroy per event |
Allocation + GC |
NodePool |
| All nodes ticking |
CPU waste |
disable update |
| No texture atlas |
Draw calls explode |
pack sprites |
| load() per frame |
I/O stall |
cache preloaded |
| Global variables |
GC hits |
scoped to class |
this.schedule() in update |
multiple timers |
use one timer |
12. When to NOT Use Cocos2d
- AAA 3D → Unreal/Unity.
- Web-only lightweight → Phaser, vanilla Canvas.
- Scripting-heavy desktop → Godot or Unity.
- Console-first → Unreal or Unity.
13. References
skills/game/game-development/cocos2d-patterns/SKILL.md — Cocos2d-x architecture deep dive
skills/game/game-engine/patterns/SKILL.md — engine design pattern catalog
skills/game/multiplayer-netcode/SKILL.md — networking approach reference
skills/game/game-development/vulkan/SKILL.md — low-level GPU rendering (mobile/desktop)
1---2name: cocos2d3description: Expert game development with Cocos2d-x / Cocos Creator - node tree, components, rendering (OpenGL ES/Metal/Vulkan), physics (Box2D), audio, UI, multi-platform build, and performance.4---56# Cocos2d-x / Cocos Creator Deep Engineering Guide78Cocos2d is a family of open-source game frameworks for 2D (and now 3D in Creator) with strong mobile focus. Cocos2d-x is the C++ core; Cocos Creator is the full editor + scene system built on top. This guide focuses on Cocos Creator 3.x (which uses Cocos2d-x under the hood).910## 1. Engine Architecture1112```13Cocos Creator 3.x14 Application15 Scene -> Node tree16 Component (Script, Render, Audio, UI, Physics...)17 Scheduler (main loop): tick() -> update() -> lateUpdate()18 Director: scene management, frame pacing19```2021- **Director** is the central controller; `director.mainLoop()` runs the frame.22- **Nodes** are the tree; **Components** (scripts) attach behavior.23- **Scheduler**: manages `update()`, `lateUpdate()`, `physicsUpdate()` with priorities.2425### 1.1 Update Order2627```28fixedUpdate() // physics substeps (if using Box2D)29update() // gameplay logic per frame30lateUpdate() // camera, UI follow31render() // GPU submit32```3334Rules:35- Node movement in physics: `move()` or set `RigidBody3D.velocity` in `fixedUpdate`.36- Visual interpolation: `node.setPosition(lerp(...))` in `update()`.3738## 2. The Node-Component Model3940```typescript41import { Component, _decorator } from 'cc';42const { ccclass, property } = _decorator;4344@ccclass('Player')45export class Player extends Component {46 @property speed: number = 10;4748 update(deltaTime: number) {49 // movement, animation, input50 }5152 onCollisionEnter(other: Collider) {53 // physics callback54 }55}56```5758### 2.1 Pattern: Event-Driven5960```typescript61// Emit62this.node.emit('damage', amount);63// Listen64this.node.on('damage', this.onDamage, this);65```6667- `node.on()`: listen on the same node or bubble up.68- `targetOff()`: remove all listeners on cleanup.69- Use typed events where possible (Cocos Creator 3.x supports `EventTarget`).7071### 2.2 Prefab Instantiation7273```typescript74import { instantiate, Prefab, resources } from 'cc';75const bullet = instantiate(this.bulletPrefab);76bullet.setPosition(this.node.worldPosition);77director.getScene().addChild(bullet);78```7980Rule: cache `prefab` references via `@property(Prefab)`, never load per frame.8182## 3. Rendering8384### 3.1 Pipeline Backends8586| Platform | Renderer |87|----------|----------|88| Desktop/Mobile (GL) | OpenGL ES 3.1+ |89| iOS / Metal devices | Metal |90| Android Vulkan | Vulkan (via Cocos 3.x) |91| Web | WebGL 2.0 |9293### 3.2 Draw Calls & Batching9495- `Sprite` with the same texture/atlas: automatically batched by `SpriteBatch`/`RenderBatch`.96- Use texture atlases (`TexturePacker`) aggressively.97- UI: `UIOpacity` only on dynamic nodes; static UI should be grouped under a single `Opacity` parent.9899### 3.3 Custom Rendering (Cocos Creator 3.x)100101```typescript102@ccclass('CustomEffect')103export class CustomEffect extends RenderableComponent {104 getRenderPipeline() { return 'Builtin'; }105 // use this.getMaterial(0) to change uniforms106}107```108109- `RenderPipeline` (Forward, Deferred) set in Project Settings.110- 2D games use Forward renderer; 3D can opt Deferred.111112## 4. Physics113114- Cocos Creator 3.x uses **Bullet** (3D) / **Box2D** (2D) via `physics-3d` / `physics-2d`.115- Nodes: `Collider2D`/`Collider3D` + `RigidBody2D`/`RigidBody3D`.116- Contact callbacks: `onBeginContact`, `onEndContact`.117- Layers: `physicsGroup` in Project Settings.118119### 4.1 Character Controller120121```typescript122const controller = this.node.getComponent(CharacterController);123controller.move(dir, deltaTime);124```125126- For platformers: `RigidBody2D` + `BoxCollider2D`, manual velocity control.127- For 3D: `CharacterController3D` from `cc` (or use Box2D bullet).128129## 5. Audio130131- `AudioSource` component: `play()`, `stop()`, `volume`, `loop`.132- Audio files: MP3 (loop), OGG (streaming), WAV (small SFX).133- Preload audio on scene load; never load audio per event.134135## 6. UI (UI Toolkit equivalent: Cocos UI)136137- Nodes: `Sprite`, `Label`, `Button`, `Slider`, `ScrollView`, `RichText`.138- Layout: `Layout` component (horizontal/vertical/grid).139- Anchor points: `[0-1, 0-1]` (unlike Unity's pivot).140- `Canvas` node as root of UI tree; camera renders to UI layer.141- `Widget` component for responsive layout (attach to parent edges).142143## 7. Scripting Languages144145| Option | Use |146|--------|-----|147| **TypeScript** | Primary, first-class support in Cocos Creator |148| **C++ (Cocos2d-x)** | Engine extensions, GDExtension-like via `bindings` |149| **Lua** | Legacy Cocos2d-x; not primary in Creator 3.x |150151### 7.1 TypeScript Rules152153- Use `@property` decorators to expose fields.154- Typed node references: `@property(Node) target: Node;`.155- `this.node`: current node; `this.node.parent`: tree up.156- `director.loadScene('sceneName')` to switch scenes.157158## 8. Multiplayer159160- Cocos Creator has no built-in high-level netcode; use:161 - WebSocket/HTTP for REST APIs.162 - Native TCP/UDP via C++ bindings for real-time.163 - Socket.IO plugin for event-based messaging.164- Rollback/interpolation implemented in user code; see `skills/game/multiplayer-netcode/SKILL.md`.165166## 9. Asset Pipeline & Build167168- **Assets/**: `.ts` scripts, `.prefab`, `.scene`, `.texture`, `.anim`.169- Resource Manager (`resources.load()`): load by path within `resources/` folder.170- `AssetManager` for runtime loading, scene loading.171- Build: Editor -> Build -> platform (iOS/Android/Web/Desktop) -> compile (Xcode/Gradle/Webpack).172- Remote asset bundle: `AssetManager.loadBundle` from CDN for hot updates.173174## 10. Performance Rules1751761. Profile: Cocos DevTools, Performance Monitor, `console.time()`.1772. Node count: keep <5000 active; use culling (`NodePool` or visibility checks).1783. Object pool: `NodePool` for bullets/enemies; never `instantiate`/`destroy` per event.1794. `destroy()` is deferred; `removeFromParent()` + pool recycling is faster.1805. Light count: keep 3D dynamic lights < 4 on mobile.1816. Audio: limit simultaneous audio sources (3-5 on mobile).1827. Memory: release unused `AssetManager` bundles explicitly.183184### 10.1 Frame Budget (Mobile @ 30fps = 33ms)185186| System | Budget |187|--------|--------|188| Gameplay | 8ms |189| Physics | 5ms |190| Render (CPU) | 8ms |191| Audio | 2ms |192| GC / misc | 5ms |193| GPU | 16.6ms (GPU-bound, overlap CPU) |194195## 11. Anti-Patterns196197| Anti-pattern | Consequence | Fix |198|--------------|-------------|-----|199| Instantiate/destroy per event | Allocation + GC | NodePool |200| All nodes ticking | CPU waste | disable update |201| No texture atlas | Draw calls explode | pack sprites |202| load() per frame | I/O stall | cache preloaded |203| Global variables | GC hits | scoped to class |204| `this.schedule()` in update | multiple timers | use one timer |205206## 12. When to NOT Use Cocos2d207208- AAA 3D → Unreal/Unity.209- Web-only lightweight → Phaser, vanilla Canvas.210- Scripting-heavy desktop → Godot or Unity.211- Console-first → Unreal or Unity.212213## 13. References214215- `skills/game/game-development/cocos2d-patterns/SKILL.md` — Cocos2d-x architecture deep dive216- `skills/game/game-engine/patterns/SKILL.md` — engine design pattern catalog217- `skills/game/multiplayer-netcode/SKILL.md` — networking approach reference218- `skills/game/game-development/vulkan/SKILL.md` — low-level GPU rendering (mobile/desktop)