Command Palette

Search for a command to run...

Назад к скиллам
скилл № 90476

cocos2d-patterns

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…

БесплатноБез исполняемых скриптов
j4flmaoот j4flmao★ 47 звёзд на GitHub

Установить cocos2d-patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Об этом скилле

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

  • Cocos2d-x version and language (C++, Lua, JS bindings)
  • Platform targets
  • Observed performance or memory problem

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
  • Director::runWithScene() sets the initial scene.
  • Director::replaceScene() swaps current scene (with optional transition).
  • Director::pushScene()/popScene() for pause menus layered over gameplay.

1.1 Frame pacing

  • Director::setAnimationInterval(1.0/60.0) sets the desired FPS.
  • On mobile, respect setProjection/retina scaling (CC_CONTENT_SCALE_FACTOR).

2. Scene Graph & Node Tree

  • Node is the base: position, rotation, scale, skew, opacity, anchor point, children, z-order.
  • Transform hierarchy: local transforms multiplied up the chain → world MVP.
  • addChild(node, zOrder).
  • Depth-first traversal via visit().

2.1 Transforms & Anchor Points

  • setAnchorPoint() sets the pivot in normalised content-size units: plain Node defaults to (0,0), Sprite to (0.5,0.5); the origin is bottom-left, y up.
  • 2D games: work with Vec2/Size; world coordinates via convertToWorldSpaceAR.
  • Be careful with parent scale/rotation affecting child positions — standard matrix chaining.

2.2 Event System

  • EventListenerTouchOneByOne / EventListenerTouchAllAtOnce.
  • Custom events: EventDispatcher::dispatchCustomEvent("name", &data).
  • Register with _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, node): priority follows draw order and the listener is removed with the node. Fixed-priority listeners must be removed manually.

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

  • Since v3 the Renderer auto-batches consecutive TrianglesCommands with the same texture, shader (GLProgramState) and blend func, so SpriteBatchNode is rarely needed.
  • Atlases (SpriteFrameCache + TexturePacker plists) keep consecutive sprites on one texture.
  • Sorting: opaque up-front (no blending), transparent sorted back-to-front.

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

  • Subclass Node and override draw(Renderer* renderer, const Mat4& transform, uint32_t flags) to push a TrianglesCommand or CustomCommand.
  • Renderer supports custom geometry (a quad list) — great for particle trails, vector UI.

4. Action System (Animation Without Code)

  • Actions: MoveTo, Sequence, Spawn, RepeatForever, EaseIn.
  • node->runAction(...); the ActionManager (a scheduled update on the main thread) steps all actions each frame.
  • Hierarchy: Sequence/Spawn composite actions; ActionInterval for timed.
  • Director::getScheduler() controls update priorities of actions.

4.1 Scheduler

  • scheduler->schedule(...) with time intervals; update(dt) for every frame.
  • scheduleUpdate() / unscheduleUpdate() on nodes.
  • Pause/Resume: scheduler respects Director::pause().

5. Physics in Cocos2d-x

  • 2D: the integrated PhysicsWorld/PhysicsBody API wraps Chipmunk2D (CC_USE_CHIPMUNK); Box2D is available for direct use.
  • 3D: Physics3DWorld wraps Bullet (CC_USE_3D_PHYSICS).
  • PhysicsBody::createBox, PhysicsWorld integrated to scene.
  • Fixed timestep
Полный SKILL.md на GitHub

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл cocos2d-patterns?

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).

Как установить скилл cocos2d-patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл cocos2d-patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить cocos2d-patterns с