Cocos2d patterns

From j4flmao/agent-skills · View interactive version

Cocos2d patterns is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about Cocos2d-x internals: the Director loop, scene graph, render queue and auto-batching, event dispatcher, or Ref/retain/release and autorelease pools. Explains engine internals to write fast C++ game code. Not for Cocos Creator gameplay scripting (use cocos2d).

How to use this skill

Skill file

Cocos2d-x Architectural Patterns

Purpose

Cocos2d-x has a mature scene-graph architecture centered on the Director and Node tree. Understanding its internals lets you design for performance: batched rendering, minimal state changes, and memory discipline on mobile.

Agent Protocol

Trigger

"cocos2d-x internals", "cocos director", "cocos scene graph", "cocos render queue", "cocos memory management".

Input Context

Output Artifact

Architecture guidance and C++ code. No file unless requested.

Response Format

Area: {director | scene graph | renderer | events | memory}
Finding: {cause}
Fix: {code}
Verify: {draw-call / memory measurement}

1. The Director Lifecycle

Status note: Cocos2d-x's last major release is 4.0 (2019) and it is no longer actively developed; Cocos Creator 3.x (whose native runtime evolved from Cocos2d-x) is the maintained product. Use this skill for existing Cocos2d-x codebases.

The Director singleton drives the game.

Director::mainLoop()
  -> calculateDeltaTime()
  -> update()         // scheduled updates + physics step (if enabled)
  -> drawScene()      // render current scene

1.1 Frame pacing

2. Scene Graph & Node Tree

2.1 Transforms & Anchor Points

2.2 Event System

3. Rendering Architecture: The Render Queue

Draw calls are NOT issued during traversal. Node::visit() pushes RenderCommands into a Renderer queue:

visit() -> pushCommand(RenderCommand)  for each node
Renderer::render() -> sort commands (by z-order; transparent after opaque)
                   -> group by texture/shader to batch draw calls
                   -> flush GPU commands

3.1 Batching Strategy

3.2 Reducing Draw Calls (mobile gold)

  1. Pack art into atlases → fewer texture switches.
  2. Keep draw order grouped by atlas (children of one parent from one atlas).
  3. Avoid per-sprite custom shaders/uniforms — each unique GLProgramState breaks the batch.
  4. Avoid per-node opacity/rotation trick for static UI; group static UI into one node.
  5. Disable depth test for 2D when not needed.

3.3 Custom Rendering

4. Action System (Animation Without Code)

4.1 Scheduler

5. Physics in Cocos2d-x

5.1 Sensor pattern

Mark the shape as a sensor (PhysicsShape::setSensor(true)), set contact-test bitmasks, and handle EventListenerPhysicsContact::onContactBegin (return false to skip collision response).

6. Memory & Resource Management

6.1 Pooling Pattern

// Cocos2d-x has no built-in pool; cocos2d::Vector retains its elements.
class BulletPool {
public:
    Sprite* acquire() {
        if (_free.empty()) return Sprite::createWithSpriteFrameName("bullet.png");
        Sprite* b = _free.back();        // still retained by _free
        b->retain();
        _free.popBack();
        b->autorelease();                // balance the extra retain
        return b;
    }
    void release(Sprite* b) {
        _free.pushBack(b);               // retain before detaching
        b->removeFromParentAndCleanup(true);
    }
private:
    Vector<Sprite*> _free;
};

7. Cross-Platform Build Pattern

7.1 Cocos Creator 3.x vs Cocos2d-x

| | Cocos2d-x (C++) | Cocos Creator (TS/editor) |

|--|------------------|---------------------------|

| Language | C++ | TypeScript |

| Rendering | OpenGL ES/Metal | Vulkan/GL/Metal (multibackend) |

| Editor | none (code-first) | full editor + scene system |

| Use case | perf-critical, engine-level | team-based game dev |

8. Common Anti-Patterns

| Anti-pattern | Consequence | Fix |

|--------------|-------------|-----|

| One texture per sprite | Draw call explosion | atlas + batch node |

| per-node retain() leaks | memory growth | pooled/refcache |

| Actions recreated each frame | alloc churn | reuse cached actions |

| Global Director misuse in logic | scene-restart bugs | keep in scene node |

| blocking file loads | UI stalls | async load + cache |

9. Decision Tree

flowchart TD
    A{2D game?} -->|Yes| B{Same texture heavy?}
    A -->|No| C[Use full 3D engine instead]
    B -->|Yes| D[SpriteBatchNode + Atlas]
    B -->|No| E[Standard Sprite renderer]
    D --> F[pool + async load]
    E --> F

10. References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.