
Cocos2d X
- 9 installs
- 1 repo stars
- Updated July 29, 2026
- full-statck-skills/cocos-skills
Guidance for the Cocos2d-x v4 game engine covering scene graph, sprites, actions, physics, rendering, shaders, and platform deployment.
About
Covers Cocos2d-x v4 core concepts including nodes, sprites, scenes, actions, input handling, Box2D physics, rendering, and shaders. A game developer uses it to build Cocos2d-x games, set up the environment, and deploy across platforms.
- Node/Sprite/Scene/Action core concepts and scene management
- Box2D physics, rendering pipeline, shaders, and multi-platform deployment
Cocos2d X by the numbers
- 9 all-time installs (skills.sh)
- Ranked #198 of 247 Game Development skills by installs in the Skillselion catalog
- Data as of Jul 30, 2026 (Skillselion catalog sync)
npx skills add https://github.com/full-statck-skills/cocos-skills --skill cocos2d-xAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 9 |
|---|---|
| repo stars | ★ 1 |
| Last updated | July 29, 2026 |
| Repository | full-statck-skills/cocos-skills ↗ |
What it does
Guidance for the Cocos2d-x v4 game engine covering scene graph, sprites, actions, physics, rendering, shaders, and platform deployment.
Files
When to use this skill
Use this skill whenever the user wants to:
- Create Cocos2d-x v4 games or applications
- Learn Cocos2d-x v4 core concepts (Node, Sprite, Scene, Action)
- Set up Cocos2d-x v4 development environment
- Work with sprites, textures, animations, and labels
- Implement scene management and node lifecycle
- Handle input events (touch, mouse, keyboard)
- Use physics engine (Box2D) and collision detection
- Implement rendering pipeline, shaders, and particle systems
- Build and deploy games for multiple platforms (Windows, macOS, Linux, Android, iOS)
- Use CMake build system and command-line tools
- Migrate from older Cocos2d-x versions
- Extend engine with custom rendering and script bindings
How to use this skill
To work with Cocos2d-x v4:
1. Identify the topic from the user's request:
- Engine overview/了解引擎 →
examples/getting-started/about-engine.md - Quick start/快速上手 →
examples/getting-started/quick-start.md - Installation/安装配置 →
examples/getting-started/installation.md - Node and Scene/节点和场景 →
examples/core/node-scene.md - Sprite/精灵 →
examples/core/sprite.md - Texture/纹理 →
examples/core/texture.md - Animation/动画 →
examples/core/animation.md - Action/动作 →
examples/core/action.md - Label/标签 →
examples/core/label.md - Scene management/场景管理 →
examples/core/scene.md - Input handling/输入处理 →
examples/core/input.md - Event system/事件系统 →
examples/core/event.md - Physics/物理引擎 →
examples/advanced/physics.md - Rendering/渲染 →
examples/advanced/rendering.md - Shaders/着色器 →
examples/advanced/shader.md - Particle system/粒子系统 →
examples/advanced/particle.md - Build system/构建系统 →
examples/tools/build-system.md - Platform deployment/平台部署 →
examples/tools/deployment.md
2. Load the appropriate example file from the examples/ directory:
examples/getting-started/about-engine.md- Engine overview and featuresexamples/getting-started/quick-start.md- Create first projectexamples/getting-started/installation.md- Environment setupexamples/core/node-scene.md- Node and Scene conceptsexamples/core/sprite.md- Sprite creation and manipulationexamples/core/texture.md- Texture loading and managementexamples/core/animation.md- Animation systemexamples/core/action.md- Action system and sequencesexamples/core/label.md- Label and text renderingexamples/core/scene.md- Scene management and transitionsexamples/core/input.md- Touch, mouse, and keyboard inputexamples/core/event.md- Event system and listenersexamples/advanced/physics.md- Physics engine integrationexamples/advanced/rendering.md- Rendering pipelineexamples/advanced/shader.md- Custom shadersexamples/advanced/particle.md- Particle effectsexamples/tools/build-system.md- CMake and build configurationexamples/tools/deployment.md- Platform-specific deployment
3. Follow the specific instructions in that example file for syntax, structure, and best practices
Each example file contains:
- Instructions: Overview and usage guidelines
- Syntax: API syntax and parameters
- Examples: Complete code examples with explanations
- Reference: Links to official documentation
4. Generate C++ code following Cocos2d-x v4 conventions:
- Use
USING_NS_CC;for namespace - Use
CREATE_FUNC()macro for create functions - Follow Cocos2d-x naming conventions
- Include proper error handling
- Use smart pointers where appropriate
5. Reference the official documentation:
- Official manual: https://docs.cocos.com/cocos2d-x/v4/manual/zh/
- API reference: Check
api/directory for detailed API documentation - Examples: Check
examples/directory for code examples
6. Use templates when creating new projects:
templates/project-structure.md- Standard project structuretemplates/cmake-config.md- CMake configuration examples
Doc mapping (one-to-one with official documentation)
- See examples and API files → https://docs.cocos.com/cocos2d-x/v4/manual/zh/
Core Concepts
Node System
- Node: Base class for all display objects
- Scene: Root node of the scene graph
- Sprite: Image display node
- Label: Text display node
- Node hierarchy: Parent-child relationships
Coordinate System
- Origin at bottom-left (OpenGL style)
- Anchor point for positioning
- Local and world coordinates
Action System
- Action: Base class for node transformations
- Sequence: Chain multiple actions
- Spawn: Run actions simultaneously
- Repeat: Repeat actions multiple times
- Ease: Apply easing functions
Scene Management
- Scene transitions
- Scene lifecycle (onEnter, onExit)
- Director for scene management
Input Handling
- Touch events (single and multi-touch)
- Mouse events
- Keyboard events
- Event dispatcher system
Platform Support
Cocos2d-x v4 supports:
- Desktop: Windows, macOS, Linux
- Mobile: Android, iOS
- Web: (via Cocos Creator)
Build System
- CMake: Primary build system
- Command-line tools:
cocoscommand - IDE support: Visual Studio, Xcode, Android Studio
Migration Guide
For migrating from older versions:
- Check
examples/migration/for migration guides - API changes and compatibility notes
- CMake migration from older build systems
Reference Resources
- Official Documentation: https://docs.cocos.com/cocos2d-x/v4/manual/zh/
- API Reference: See
api/directory - Examples: See
examples/directory - Templates: See
templates/directory
Keywords
cocos2d-x, cocos2d, game engine, game development, C++ game, 2D game, cross-platform game, sprite, scene, node, action, animation, physics, rendering, shader, particle system, CMake, game framework, 游戏引擎, 游戏开发, 精灵, 场景, 节点, 动作, 动画, 物理引擎, 渲染, 着色器, 粒子系统
Important Notes
1. Version: This skill covers Cocos2d-x v4 specifically 2. Language: C++ is the primary development language 3. Build System: CMake is required for building projects 4. Platform: Ensure platform-specific dependencies are installed 5. Examples: All code examples use C++ syntax 6. Memory Management: Cocos2d-x uses reference counting, be careful with retain/release cycles 7. Coordinate System: Uses OpenGL-style coordinates (origin at bottom-left) 8. Thread Safety: Most Cocos2d-x operations must be performed on the main thread
能力边界
✅ 适用场景
- 当你需要使用此技能对应的技术栈时
- 当项目需要遵循最佳实践时
- 当需要快速上手或深入理解核心概念时
⚠️ 需要注意
- 复杂业务逻辑需要结合具体场景调整
- 性能优化需要根据实际数据量评估
❌ 不适用场景
- 不相关的技术栈或框架
- 需要完全自定义的特殊场景
常见陷阱 (Gotchas)
1. 版本兼容性:注意框架版本与依赖库的兼容性,不同版本 API 可能有差异 2. 配置文件格式:配置文件格式错误是最常见的问题,建议使用编辑器的语法检查 3. 环境变量:确保所有必要的环境变量已正确设置,敏感信息不要硬编码 4. 依赖冲突:多版本共存时注意依赖冲突,使用 lock 文件锁定版本 5. 性能陷阱:大数据量场景下注意性能优化,避免 N+1 查询等常见问题
使用流程
Step 1: 环境准备
确保开发环境已安装必要的依赖和工具。
Step 2: 配置初始化
根据项目需求进行基础配置。
Step 3: 核心功能使用
按照示例代码实现核心功能。
Step 4: 测试验证
运行测试确保功能正常。
Step 5: 部署上线
完成开发后进行部署和监控。
Action(动作)系统使用指南
官方文档
参考官方文档:https://docs.cocos.com/cocos2d-x/v4/manual/zh/
概述
Action 系统用于对节点执行各种变换操作,如移动、旋转、缩放等。
基本动作
移动动作
auto sprite = Sprite::create("player.png");
this->addChild(sprite);
// 移动到指定位置
auto moveTo = MoveTo::create(2.0f, Vec2(400, 300));
sprite->runAction(moveTo);
// 相对移动
auto moveBy = MoveBy::create(1.0f, Vec2(100, 50));
sprite->runAction(moveBy);旋转动作
// 旋转到指定角度
auto rotateTo = RotateTo::create(2.0f, 90.0f);
sprite->runAction(rotateTo);
// 相对旋转
auto rotateBy = RotateBy::create(1.0f, 180.0f);
sprite->runAction(rotateBy);缩放动作
// 缩放到指定大小
auto scaleTo = ScaleTo::create(1.0f, 2.0f);
sprite->runAction(scaleTo);
// 相对缩放
auto scaleBy = ScaleBy::create(1.0f, 1.5f);
sprite->runAction(scaleBy);淡入淡出
// 淡入
auto fadeIn = FadeIn::create(1.0f);
sprite->runAction(fadeIn);
// 淡出
auto fadeOut = FadeOut::create(1.0f);
sprite->runAction(fadeOut);
// 淡入到指定透明度
auto fadeTo = FadeTo::create(1.0f, 128);
sprite->runAction(fadeTo);跳跃动作
// 跳跃到指定位置
auto jumpTo = JumpTo::create(2.0f, Vec2(400, 300), 100, 3);
sprite->runAction(jumpTo);
// 相对跳跃
auto jumpBy = JumpBy::create(1.0f, Vec2(100, 0), 50, 2);
sprite->runAction(jumpBy);组合动作
序列动作(Sequence)
// 按顺序执行多个动作
auto move1 = MoveBy::create(1.0f, Vec2(100, 0));
auto move2 = MoveBy::create(1.0f, Vec2(0, 100));
auto move3 = MoveBy::create(1.0f, Vec2(-100, 0));
auto sequence = Sequence::create(move1, move2, move3, nullptr);
sprite->runAction(sequence);同时执行(Spawn)
// 同时执行多个动作
auto move = MoveBy::create(2.0f, Vec2(200, 0));
auto rotate = RotateBy::create(2.0f, 360.0f);
auto scale = ScaleBy::create(2.0f, 1.5f);
auto spawn = Spawn::create(move, rotate, scale, nullptr);
sprite->runAction(spawn);重复动作
// 重复指定次数
auto move = MoveBy::create(1.0f, Vec2(100, 0));
auto repeat = Repeat::create(move, 3);
sprite->runAction(repeat);
// 无限重复
auto repeatForever = RepeatForever::create(move);
sprite->runAction(repeatForever);延迟动作
// 延迟执行
auto delay = DelayTime::create(2.0f);
auto move = MoveBy::create(1.0f, Vec2(100, 0));
auto sequence = Sequence::create(delay, move, nullptr);
sprite->runAction(sequence);缓动函数
使用 Ease
auto move = MoveBy::create(2.0f, Vec2(400, 0));
// 缓入
auto easeIn = EaseIn::create(move, 2.0f);
sprite->runAction(easeIn);
// 缓出
auto easeOut = EaseOut::create(move, 2.0f);
sprite->runAction(easeOut);
// 缓入缓出
auto easeInOut = EaseInOut::create(move, 2.0f);
sprite->runAction(easeInOut);
// 弹性效果
auto elastic = EaseElasticInOut::create(move, 0.5f);
sprite->runAction(elastic);
// 弹跳效果
auto bounce = EaseBounceInOut::create(move);
sprite->runAction(bounce);回调动作
// 动作完成后执行回调
auto move = MoveBy::create(2.0f, Vec2(400, 0));
auto callback = CallFunc::create([sprite](){
log("Action completed!");
sprite->setColor(Color3B::RED);
});
auto sequence = Sequence::create(move, callback, nullptr);
sprite->runAction(sequence);完整示例
class ActionDemo : public Scene
{
public:
static Scene* createScene();
virtual bool init();
CREATE_FUNC(ActionDemo);
private:
void createMovingSprite();
void createRotatingSprite();
void createScalingSprite();
};
bool ActionDemo::init()
{
if (!Scene::init())
{
return false;
}
createMovingSprite();
createRotatingSprite();
createScalingSprite();
return true;
}
void ActionDemo::createMovingSprite()
{
auto sprite = Sprite::create("player.png");
sprite->setPosition(Vec2(100, 200));
this->addChild(sprite);
// 创建来回移动的动画
auto moveRight = MoveBy::create(2.0f, Vec2(400, 0));
auto moveLeft = MoveBy::create(2.0f, Vec2(-400, 0));
auto sequence = Sequence::create(moveRight, moveLeft, nullptr);
auto repeat = RepeatForever::create(sequence);
sprite->runAction(repeat);
}
void ActionDemo::createRotatingSprite()
{
auto sprite = Sprite::create("player.png");
sprite->setPosition(Vec2(400, 300));
this->addChild(sprite);
// 持续旋转
auto rotate = RotateBy::create(2.0f, 360.0f);
auto repeat = RepeatForever::create(rotate);
sprite->runAction(repeat);
}
void ActionDemo::createScalingSprite()
{
auto sprite = Sprite::create("player.png");
sprite->setPosition(Vec2(700, 200));
this->addChild(sprite);
// 缩放动画
auto scaleUp = ScaleTo::create(1.0f, 1.5f);
auto scaleDown = ScaleTo::create(1.0f, 1.0f);
auto sequence = Sequence::create(scaleUp, scaleDown, nullptr);
auto repeat = RepeatForever::create(sequence);
sprite->runAction(repeat);
}动作管理
停止动作
// 停止所有动作
sprite->stopAllActions();
// 停止指定动作
auto action = sprite->getActionByTag(100);
if (action)
{
sprite->stopAction(action);
}
// 停止指定标签的动作
sprite->stopActionByTag(100);动作标签
auto move = MoveBy::create(2.0f, Vec2(400, 0));
move->setTag(100);
sprite->runAction(move);
// 稍后可以通过标签获取
auto action = sprite->getActionByTag(100);参考资源
- 官方文档: https://docs.cocos.com/cocos2d-x/v4/manual/zh/
- Sprite 指南:
examples/core/sprite.md - Scene 指南:
examples/core/scene.md
Animation(动画)系统使用指南
官方文档
参考官方文档:https://docs.cocos.com/cocos2d-x/v4/manual/zh/
Instructions
Animation 系统用于创建帧动画。通过 SpriteFrame 序列创建 Animation,然后使用 Animate 动作播放。
Syntax
动画创建流程
1. 加载 SpriteFrame 到缓存 2. 创建 SpriteFrame 序列 3. 使用序列创建 Animation 4. 使用 Animate 创建动作 5. 在 Sprite 上运行动作
关键类
SpriteFrameCache- 精灵帧缓存SpriteFrame- 单个精灵帧Animation- 动画对象Animate- 动画动作
Example (基本帧动画)
// 加载精灵帧到缓存
auto cache = SpriteFrameCache::getInstance();
cache->addSpriteFramesWithFile("player.plist", "player.png");
// 创建精灵帧序列
Vector<SpriteFrame*> frames;
for (int i = 1; i <= 4; i++)
{
std::string frameName = StringUtils::format("player_walk_%02d.png", i);
auto frame = cache->getSpriteFrameByName(frameName);
if (frame)
{
frames.pushBack(frame);
}
}
// 创建动画(每帧 0.1 秒)
auto animation = Animation::createWithSpriteFrames(frames, 0.1f);
// 创建动画动作
auto animate = Animate::create(animation);
// 无限循环播放
auto repeat = RepeatForever::create(animate);
// 在精灵上运行动作
auto sprite = Sprite::createWithSpriteFrameName("player_walk_01.png");
sprite->runAction(repeat);
this->addChild(sprite);Example (动画控制)
// 创建动画
auto animation = Animation::createWithSpriteFrames(frames, 0.1f);
auto animate = Animate::create(animation);
// 播放一次
sprite->runAction(animate);
// 播放指定次数
auto repeat = Repeat::create(animate, 3);
sprite->runAction(repeat);
// 无限循环
auto repeatForever = RepeatForever::create(animate);
sprite->runAction(repeatForever);
// 停止动画
sprite->stopAllActions();Example (多个动画)
class Player : public Sprite
{
public:
CREATE_FUNC(Player);
virtual bool init() override;
void playIdleAnimation();
void playWalkAnimation();
void playJumpAnimation();
private:
Animation* _idleAnimation;
Animation* _walkAnimation;
Animation* _jumpAnimation;
Animate* _currentAnimate;
};
bool Player::init()
{
if (!Sprite::init())
{
return false;
}
auto cache = SpriteFrameCache::getInstance();
cache->addSpriteFramesWithFile("player.plist", "player.png");
// 创建待机动画
Vector<SpriteFrame*> idleFrames;
for (int i = 1; i <= 2; i++)
{
auto frame = cache->getSpriteFrameByName(
StringUtils::format("player_idle_%02d.png", i));
idleFrames.pushBack(frame);
}
_idleAnimation = Animation::createWithSpriteFrames(idleFrames, 0.2f);
_idleAnimation->setRestoreOriginalFrame(true);
// 创建行走动画
Vector<SpriteFrame*> walkFrames;
for (int i = 1; i <= 4; i++)
{
auto frame = cache->getSpriteFrameByName(
StringUtils::format("player_walk_%02d.png", i));
walkFrames.pushBack(frame);
}
_walkAnimation = Animation::createWithSpriteFrames(walkFrames, 0.1f);
// 创建跳跃动画
Vector<SpriteFrame*> jumpFrames;
for (int i = 1; i <= 3; i++)
{
auto frame = cache->getSpriteFrameByName(
StringUtils::format("player_jump_%02d.png", i));
jumpFrames.pushBack(frame);
}
_jumpAnimation = Animation::createWithSpriteFrames(jumpFrames, 0.15f);
_jumpAnimation->setRestoreOriginalFrame(true);
// 默认播放待机动画
playIdleAnimation();
return true;
}
void Player::playIdleAnimation()
{
this->stopAllActions();
_currentAnimate = Animate::create(_idleAnimation);
auto repeat = RepeatForever::create(_currentAnimate);
this->runAction(repeat);
}
void Player::playWalkAnimation()
{
this->stopAllActions();
_currentAnimate = Animate::create(_walkAnimation);
auto repeat = RepeatForever::create(_currentAnimate);
this->runAction(repeat);
}
void Player::playJumpAnimation()
{
this->stopAllActions();
_currentAnimate = Animate::create(_jumpAnimation);
this->runAction(_currentAnimate);
// 跳跃动画结束后恢复待机
auto callback = CallFunc::create([this]() {
this->playIdleAnimation();
});
auto sequence = Sequence::create(_currentAnimate, callback, nullptr);
this->runAction(sequence);
}Example (动画回调)
// 创建动画
auto animation = Animation::createWithSpriteFrames(frames, 0.1f);
auto animate = Animate::create(animation);
// 动画完成回调
auto callback = CallFunc::create([sprite]() {
log("Animation finished");
sprite->setColor(Color3B::RED);
});
auto sequence = Sequence::create(animate, callback, nullptr);
sprite->runAction(sequence);Example (动画延迟)
// 创建动画
auto animation = Animation::createWithSpriteFrames(frames, 0.1f);
// 设置动画延迟(每帧之间的延迟)
animation->setDelayPerUnit(0.1f);
// 设置总延迟
animation->setDelayUnits(0.5f);
auto animate = Animate::create(animation);
sprite->runAction(animate);Reference
- 官方文档: https://docs.cocos.com/cocos2d-x/v4/manual/zh/
- Sprite 指南:
examples/core/sprite.md - Action 指南:
examples/core/action.md
Event(事件)系统使用指南
官方文档
参考官方文档:https://docs.cocos.com/cocos2d-x/v4/manual/zh/
Instructions
Cocos2d-x 使用事件分发器(EventDispatcher)来处理各种事件。事件系统支持触摸、鼠标、键盘、自定义事件等。
Syntax
事件监听器类型
EventListenerTouchOneByOne- 单点触摸事件EventListenerTouchAllAtOnce- 多点触摸事件EventListenerMouse- 鼠标事件EventListenerKeyboard- 键盘事件EventListenerCustom- 自定义事件
事件注册
_eventDispatcher->addEventListenerWithSceneGraphPriority()- 使用场景图优先级_eventDispatcher->addEventListenerWithFixedPriority()- 使用固定优先级_eventDispatcher->removeEventListener()- 移除事件监听器
Example (自定义事件)
// 定义自定义事件名称
const std::string EVENT_PLAYER_DIED = "player_died";
const std::string EVENT_SCORE_UPDATED = "score_updated";
// 创建自定义事件监听器
auto listener = EventListenerCustom::create(EVENT_PLAYER_DIED, [](EventCustom* event) {
log("Player died event received");
// 处理玩家死亡事件
});
// 注册监听器
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
// 发送自定义事件
EventCustom event(EVENT_PLAYER_DIED);
_eventDispatcher->dispatchEvent(&event);Example (事件优先级)
// 场景图优先级(推荐)
auto listener1 = EventListenerTouchOneByOne::create();
listener1->onTouchBegan = [](Touch* touch, Event* event) { return true; };
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, node1);
// 固定优先级
auto listener2 = EventListenerTouchOneByOne::create();
listener2->onTouchBegan = [](Touch* touch, Event* event) { return true; };
_eventDispatcher->addEventListenerWithFixedPriority(listener2, 100);Example (事件冒泡)
// 设置事件是否冒泡
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true); // 阻止事件继续传播
listener->onTouchBegan = [](Touch* touch, Event* event) {
return true; // 返回 true 表示处理此事件
};Example (完整事件处理示例)
class GameLayer : public Layer
{
public:
CREATE_FUNC(GameLayer);
virtual bool init() override;
private:
void setupEventListeners();
void onPlayerDied(EventCustom* event);
void onScoreUpdated(EventCustom* event);
};
bool GameLayer::init()
{
if (!Layer::init())
{
return false;
}
setupEventListeners();
return true;
}
void GameLayer::setupEventListeners()
{
// 玩家死亡事件
auto playerDiedListener = EventListenerCustom::create(
"player_died",
CC_CALLBACK_1(GameLayer::onPlayerDied, this)
);
_eventDispatcher->addEventListenerWithSceneGraphPriority(playerDiedListener, this);
// 分数更新事件
auto scoreListener = EventListenerCustom::create(
"score_updated",
CC_CALLBACK_1(GameLayer::onScoreUpdated, this)
);
_eventDispatcher->addEventListenerWithSceneGraphPriority(scoreListener, this);
}
void GameLayer::onPlayerDied(EventCustom* event)
{
log("Player died!");
// 处理玩家死亡逻辑
}
void GameLayer::onScoreUpdated(EventCustom* event)
{
int* score = static_cast<int*>(event->getUserData());
log("Score updated: %d", *score);
// 更新 UI
}Reference
- 官方文档: https://docs.cocos.com/cocos2d-x/v4/manual/zh/
- Input 指南:
examples/core/input.md
Input(输入)处理指南
官方文档
参考官方文档:https://docs.cocos.com/cocos2d-x/v4/manual/zh/
概述
Cocos2d-x 支持触摸、鼠标和键盘输入事件。
触摸事件
单点触摸
class TouchLayer : public Layer
{
public:
CREATE_FUNC(TouchLayer);
virtual bool init() override;
private:
bool onTouchBegan(Touch* touch, Event* event);
void onTouchMoved(Touch* touch, Event* event);
void onTouchEnded(Touch* touch, Event* event);
void onTouchCancelled(Touch* touch, Event* event);
};
bool TouchLayer::init()
{
if (!Layer::init())
{
return false;
}
// 创建触摸监听器
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
// 绑定回调函数
listener->onTouchBegan = CC_CALLBACK_2(TouchLayer::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(TouchLayer::onTouchMoved, this);
listener->onTouchEnded = CC_CALLBACK_2(TouchLayer::onTouchEnded, this);
listener->onTouchCancelled = CC_CALLBACK_2(TouchLayer::onTouchCancelled, this);
// 注册监听器
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
return true;
}
bool TouchLayer::onTouchBegan(Touch* touch, Event* event)
{
Vec2 location = touch->getLocation();
log("Touch began at: (%.2f, %.2f)", location.x, location.y);
return true; // 返回 true 表示要接收后续事件
}
void TouchLayer::onTouchMoved(Touch* touch, Event* event)
{
Vec2 location = touch->getLocation();
log("Touch moved to: (%.2f, %.2f)", location.x, location.y);
}
void TouchLayer::onTouchEnded(Touch* touch, Event* event)
{
Vec2 location = touch->getLocation();
log("Touch ended at: (%.2f, %.2f)", location.x, location.y);
}
void TouchLayer::onTouchCancelled(Touch* touch, Event* event)
{
log("Touch cancelled");
}多点触摸
class MultiTouchLayer : public Layer
{
public:
CREATE_FUNC(MultiTouchLayer);
virtual bool init() override;
private:
void onTouchesBegan(const std::vector<Touch*>& touches, Event* event);
void onTouchesMoved(const std::vector<Touch*>& touches, Event* event);
void onTouchesEnded(const std::vector<Touch*>& touches, Event* event);
};
bool MultiTouchLayer::init()
{
if (!Layer::init())
{
return false;
}
auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(MultiTouchLayer::onTouchesBegan, this);
listener->onTouchesMoved = CC_CALLBACK_2(MultiTouchLayer::onTouchesMoved, this);
listener->onTouchesEnded = CC_CALLBACK_2(MultiTouchLayer::onTouchesEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
return true;
}
void MultiTouchLayer::onTouchesBegan(const std::vector<Touch*>& touches, Event* event)
{
log("Touches began: %zu touches", touches.size());
for (auto touch : touches)
{
Vec2 location = touch->getLocation();
log(" Touch at: (%.2f, %.2f)", location.x, location.y);
}
}鼠标事件
class MouseLayer : public Layer
{
public:
CREATE_FUNC(MouseLayer);
virtual bool init() override;
private:
void onMouseDown(Event* event);
void onMouseUp(Event* event);
void onMouseMove(Event* event);
void onMouseScroll(Event* event);
};
bool MouseLayer::init()
{
if (!Layer::init())
{
return false;
}
auto listener = EventListenerMouse::create();
listener->onMouseDown = CC_CALLBACK_1(MouseLayer::onMouseDown, this);
listener->onMouseUp = CC_CALLBACK_1(MouseLayer::onMouseUp, this);
listener->onMouseMove = CC_CALLBACK_1(MouseLayer::onMouseMove, this);
listener->onMouseScroll = CC_CALLBACK_1(MouseLayer::onMouseScroll, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
return true;
}
void MouseLayer::onMouseDown(Event* event)
{
EventMouse* mouseEvent = static_cast<EventMouse*>(event);
Vec2 location = mouseEvent->getLocationInView();
log("Mouse down at: (%.2f, %.2f)", location.x, location.y);
}
void MouseLayer::onMouseScroll(Event* event)
{
EventMouse* mouseEvent = static_cast<EventMouse*>(event);
float scrollY = mouseEvent->getScrollY();
log("Mouse scroll: %.2f", scrollY);
}键盘事件
class KeyboardLayer : public Layer
{
public:
CREATE_FUNC(KeyboardLayer);
virtual bool init() override;
private:
void onKeyPressed(EventKeyboard::KeyCode keyCode, Event* event);
void onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event);
};
bool KeyboardLayer::init()
{
if (!Layer::init())
{
return false;
}
auto listener = EventListenerKeyboard::create();
listener->onKeyPressed = CC_CALLBACK_2(KeyboardLayer::onKeyPressed, this);
listener->onKeyReleased = CC_CALLBACK_2(KeyboardLayer::onKeyReleased, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
return true;
}
void KeyboardLayer::onKeyPressed(EventKeyboard::KeyCode keyCode, Event* event)
{
switch (keyCode)
{
case EventKeyboard::KeyCode::KEY_LEFT_ARROW:
log("Left arrow pressed");
break;
case EventKeyboard::KeyCode::KEY_RIGHT_ARROW:
log("Right arrow pressed");
break;
case EventKeyboard::KeyCode::KEY_SPACE:
log("Space pressed");
break;
default:
break;
}
}拖拽示例
class DragLayer : public Layer
{
public:
CREATE_FUNC(DragLayer);
virtual bool init() override;
private:
bool onTouchBegan(Touch* touch, Event* event);
void onTouchMoved(Touch* touch, Event* event);
void onTouchEnded(Touch* touch, Event* event);
Sprite* _draggedSprite;
bool _isDragging;
};
bool DragLayer::init()
{
if (!Layer::init())
{
return false;
}
// 创建可拖拽的精灵
_draggedSprite = Sprite::create("player.png");
_draggedSprite->setPosition(Vec2(400, 300));
this->addChild(_draggedSprite);
_isDragging = false;
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = CC_CALLBACK_2(DragLayer::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(DragLayer::onTouchMoved, this);
listener->onTouchEnded = CC_CALLBACK_2(DragLayer::onTouchEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
return true;
}
bool DragLayer::onTouchBegan(Touch* touch, Event* event)
{
Vec2 location = touch->getLocation();
Rect rect = _draggedSprite->getBoundingBox();
if (rect.containsPoint(location))
{
_isDragging = true;
return true;
}
return false;
}
void DragLayer::onTouchMoved(Touch* touch, Event* event)
{
if (_isDragging)
{
Vec2 location = touch->getLocation();
_draggedSprite->setPosition(location);
}
}
void DragLayer::onTouchEnded(Touch* touch, Event* event)
{
_isDragging = false;
}参考资源
- 官方文档: https://docs.cocos.com/cocos2d-x/v4/manual/zh/
- Event 系统:
examples/core/event.md
Label(标签)使用指南
官方文档
参考官方文档:https://docs.cocos.com/cocos2d-x/v4/manual/zh/
Instructions
Label 用于在游戏中显示文本。Cocos2d-x 支持多种标签类型:TTF、BMFont、CharMap。
Syntax
Label 类型
Label::createWithTTF()- 使用 TTF 字体文件Label::createWithBMFont()- 使用 BMFont 位图字体Label::createWithCharMap()- 使用字符映射Label::createWithSystemFont()- 使用系统字体
Label 属性
setString()- 设置文本内容setFontSize()- 设置字体大小setTextColor()- 设置文本颜色setAlignment()- 设置对齐方式setDimensions()- 设置文本区域大小
Example (TTF 标签)
// 使用 TTF 字体文件创建标签
auto label = Label::createWithTTF("Hello Cocos2d-x", "fonts/Marker Felt.ttf", 24);
label->setPosition(Vec2(400, 300));
label->setColor(Color3B::WHITE);
this->addChild(label);Example (系统字体标签)
// 使用系统字体创建标签
auto label = Label::createWithSystemFont("Hello World", "Arial", 24);
label->setPosition(Vec2(400, 300));
this->addChild(label);Example (BMFont 标签)
// 使用 BMFont 位图字体创建标签
auto label = Label::createWithBMFont("fonts/bitmap-font.fnt", "Hello");
label->setPosition(Vec2(400, 300));
this->addChild(label);Example (标签属性设置)
auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);
// 设置文本
label->setString("New Text");
// 设置字体大小
label->setFontSize(32);
// 设置文本颜色
label->setTextColor(Color4B::RED);
label->setColor(Color3B::GREEN);
// 设置对齐方式
label->setAlignment(TextHAlignment::CENTER, TextVAlignment::CENTER);
// 设置文本区域(自动换行)
label->setDimensions(200, 100);
label->enableWrap(true);
// 设置行间距
label->setLineSpacing(10);
// 设置透明度
label->setOpacity(200);Example (多行文本)
auto label = Label::createWithTTF(
"This is a long text that will wrap to multiple lines",
"fonts/Marker Felt.ttf",
20
);
// 设置文本区域大小(自动换行)
label->setDimensions(300, 0); // 宽度 300,高度自动
label->enableWrap(true);
label->setAlignment(TextHAlignment::LEFT, TextVAlignment::TOP);
label->setPosition(Vec2(400, 300));
this->addChild(label);Example (标签效果)
auto label = Label::createWithTTF("Hello", "fonts/Marker Felt.ttf", 48);
// 描边效果
label->enableOutline(Color4B::BLACK, 2);
// 阴影效果
label->enableShadow(Color4B::GRAY, Size(2, -2), 0);
// 发光效果
label->enableGlow(Color4B::YELLOW);
label->setPosition(Vec2(400, 300));
this->addChild(label);Example (动态更新文本)
class ScoreLabel : public Label
{
public:
CREATE_FUNC(ScoreLabel);
virtual bool init() override;
void updateScore(int score);
private:
int _score;
};
bool ScoreLabel::init()
{
if (!Label::initWithTTF("Score: 0", "fonts/Marker Felt.ttf", 24))
{
return false;
}
_score = 0;
this->setPosition(Vec2(100, 500));
this->setColor(Color3B::WHITE);
return true;
}
void ScoreLabel::updateScore(int score)
{
_score += score;
std::string text = StringUtils::format("Score: %d", _score);
this->setString(text);
}Example (富文本标签)
// 创建富文本标签
auto richText = RichText::create();
richText->setContentSize(Size(400, 100));
// 添加普通文本
auto text1 = RichElementText::create(1, Color3B::WHITE, 255, "Hello ", "fonts/Marker Felt.ttf", 24);
richText->pushBackElement(text1);
// 添加彩色文本
auto text2 = RichElementText::create(2, Color3B::RED, 255, "Cocos2d-x", "fonts/Marker Felt.ttf", 24);
richText->pushBackElement(text2);
// 添加图片
auto image = RichElementImage::create(3, Color3B::WHITE, 255, "icon.png");
richText->pushBackElement(image);
richText->setPosition(Vec2(400, 300));
this->addChild(richText);Reference
- 官方文档: https://docs.cocos.com/cocos2d-x/v4/manual/zh/
- Sprite 指南:
examples/core/sprite.md
Node 和 Scene 基础
官方文档
参考官方文档:https://docs.cocos.com/cocos2d-x/v4/manual/zh/
Instructions
Node 是 Cocos2d-x 中所有显示对象的基础类,Scene 是场景图的根节点。理解 Node 和 Scene 的关系是使用 Cocos2d-x 的基础。
Syntax
Node 基础
- 所有显示对象都继承自
Node - Node 支持位置、旋转、缩放、锚点等变换
- Node 可以添加子节点形成树结构
- Node 有生命周期方法:
onEnter(),onExit(),onEnterTransitionDidFinish(),onExitTransitionDidStart()
Scene 基础
- Scene 继承自 Node,是场景图的根节点
- 通过 Director 管理场景切换
- 一个应用同时只能有一个运行的 Scene
Example (创建基本 Node)
#include "cocos2d.h"
USING_NS_CC;
// 创建一个简单的 Node
auto node = Node::create();
node->setPosition(Vec2(400, 300));
node->setRotation(45.0f);
node->setScale(1.5f);
node->setAnchorPoint(Vec2(0.5f, 0.5f));
// 添加到场景
scene->addChild(node);Example (Node 层次结构)
// 创建父节点
auto parent = Node::create();
parent->setPosition(Vec2(400, 300));
// 创建子节点
auto child1 = Sprite::create("sprite1.png");
child1->setPosition(Vec2(-50, 0)); // 相对于父节点
parent->addChild(child1);
auto child2 = Sprite::create("sprite2.png");
child2->setPosition(Vec2(50, 0)); // 相对于父节点
parent->addChild(child2);
// 添加到场景
scene->addChild(parent);Example (创建 Scene)
class HelloWorld : public Scene
{
public:
static Scene* createScene();
virtual bool init();
CREATE_FUNC(HelloWorld);
};
Scene* HelloWorld::createScene()
{
return HelloWorld::create();
}
bool HelloWorld::init()
{
if (!Scene::init())
{
return false;
}
auto visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
// 添加内容到场景
auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);
label->setPosition(Vec2(origin.x + visibleSize.width/2,
origin.y + visibleSize.height - label->getContentSize().height));
this->addChild(label, 1);
return true;
}Example (Node 生命周期)
class MyNode : public Node
{
public:
CREATE_FUNC(MyNode);
virtual bool init() override;
virtual void onEnter() override;
virtual void onEnterTransitionDidFinish() override;
virtual void onExit() override;
virtual void onExitTransitionDidStart() override;
};
bool MyNode::init()
{
if (!Node::init())
{
return false;
}
log("Node initialized");
return true;
}
void MyNode::onEnter()
{
Node::onEnter();
log("Node entered");
}
void MyNode::onEnterTransitionDidFinish()
{
Node::onEnterTransitionDidFinish();
log("Node transition finished");
}
void MyNode::onExit()
{
Node::onExit();
log("Node exited");
}
void MyNode::onExitTransitionDidStart()
{
Node::onExitTransitionDidStart();
log("Node transition started");
}Example (坐标系统)
// Cocos2d-x 使用 OpenGL 坐标系
// 原点在左下角,Y 轴向上
auto sprite = Sprite::create("player.png");
// 设置位置(世界坐标)
sprite->setPosition(Vec2(400, 300));
// 设置锚点(0.5, 0.5 表示中心)
sprite->setAnchorPoint(Vec2(0.5f, 0.5f));
// 获取世界坐标
Vec2 worldPos = sprite->getPosition();
// 转换为节点本地坐标
Vec2 localPos = sprite->convertToNodeSpace(worldPos);
// 转换为世界坐标
Vec2 worldPos2 = sprite->convertToWorldSpace(localPos);Example (Node 变换)
auto node = Node::create();
// 位置
node->setPosition(Vec2(400, 300));
node->setPositionX(400);
node->setPositionY(300);
// 旋转(角度)
node->setRotation(45.0f);
node->setRotationX(30.0f);
node->setRotationY(60.0f);
// 缩放
node->setScale(2.0f); // 统一缩放
node->setScaleX(1.5f); // X 轴缩放
node->setScaleY(0.8f); // Y 轴缩放
// 锚点
node->setAnchorPoint(Vec2(0.5f, 0.5f)); // 中心
node->setAnchorPoint(Vec2(0.0f, 0.0f)); // 左下角
node->setAnchorPoint(Vec2(1.0f, 1.0f)); // 右上角
// 可见性
node->setVisible(true);
node->setVisible(false);
// 透明度
node->setOpacity(255); // 完全不透明
node->setOpacity(128); // 半透明
node->setOpacity(0); // 完全透明Reference
- 官方文档: https://docs.cocos.com/cocos2d-x/v4/manual/zh/
- Scene 指南:
examples/core/scene.md - Sprite 指南:
examples/core/sprite.md
Scene(场景)管理指南
官方文档
参考官方文档:https://docs.cocos.com/cocos2d-x/v4/manual/zh/
概述
Scene 是场景图的根节点,通过 Director 管理场景的切换和生命周期。
创建场景
基本场景
class GameScene : public Scene
{
public:
static Scene* createScene();
virtual bool init();
CREATE_FUNC(GameScene);
};
Scene* GameScene::createScene()
{
return GameScene::create();
}
bool GameScene::init()
{
if (!Scene::init())
{
return false;
}
// 场景初始化代码
auto label = Label::createWithTTF("Game Scene", "fonts/Marker Felt.ttf", 24);
label->setPosition(Vec2(400, 300));
this->addChild(label);
return true;
}场景切换
直接切换
// 切换到新场景
auto newScene = GameScene::createScene();
Director::getInstance()->replaceScene(newScene);带过渡效果的切换
// 淡入淡出过渡
auto transition = TransitionFade::create(1.0f, GameScene::createScene());
Director::getInstance()->replaceScene(transition);
// 翻页过渡
auto transition = TransitionPageTurn::create(1.0f, GameScene::createScene(), false);
Director::getInstance()->replaceScene(transition);
// 滑动过渡
auto transition = TransitionSlideInR::create(1.0f, GameScene::createScene());
Director::getInstance()->replaceScene(transition);场景生命周期
class GameScene : public Scene
{
public:
virtual void onEnter() override;
virtual void onEnterTransitionDidFinish() override;
virtual void onExit() override;
virtual void onExitTransitionDidStart() override;
};
void GameScene::onEnter()
{
Scene::onEnter();
log("Scene entered");
// 场景进入时的初始化
}
void GameScene::onEnterTransitionDidFinish()
{
Scene::onEnterTransitionDidFinish();
log("Scene transition finished");
// 过渡完成后的操作
}
void GameScene::onExit()
{
Scene::onExit();
log("Scene exiting");
// 场景退出时的清理
}
void GameScene::onExitTransitionDidStart()
{
Scene::onExitTransitionDidStart();
log("Scene transition started");
// 过渡开始时的操作
}场景层次结构
bool GameScene::init()
{
if (!Scene::init())
{
return false;
}
// 背景层
auto backgroundLayer = Layer::create();
auto bgSprite = Sprite::create("background.png");
bgSprite->setPosition(Vec2(400, 300));
backgroundLayer->addChild(bgSprite);
this->addChild(backgroundLayer, 0);
// 游戏层
auto gameLayer = Layer::create();
// 添加游戏对象
this->addChild(gameLayer, 1);
// UI 层
auto uiLayer = Layer::create();
// 添加 UI 元素
this->addChild(uiLayer, 2);
return true;
}Director 使用
获取 Director 实例
auto director = Director::getInstance();获取窗口信息
auto director = Director::getInstance();
auto visibleSize = director->getVisibleSize();
Vec2 origin = director->getVisibleOrigin();
Vec2 center = Vec2(visibleSize.width/2 + origin.x,
visibleSize.height/2 + origin.y);暂停和恢复
// 暂停场景
Director::getInstance()->pause();
// 恢复场景
Director::getInstance()->resume();完整示例
class MenuScene : public Scene
{
public:
static Scene* createScene();
virtual bool init();
CREATE_FUNC(MenuScene);
private:
void onPlayButtonClicked(Ref* sender);
};
bool MenuScene::init()
{
if (!Scene::init())
{
return false;
}
auto visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
// 标题
auto title = Label::createWithTTF("My Game", "fonts/Marker Felt.ttf", 48);
title->setPosition(Vec2(origin.x + visibleSize.width/2,
origin.y + visibleSize.height - 100));
this->addChild(title, 1);
// 开始按钮
auto playButton = MenuItemImage::create(
"button_play.png",
"button_play_selected.png",
CC_CALLBACK_1(MenuScene::onPlayButtonClicked, this));
playButton->setPosition(Vec2(origin.x + visibleSize.width/2,
origin.y + visibleSize.height/2));
auto menu = Menu::create(playButton, nullptr);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
return true;
}
void MenuScene::onPlayButtonClicked(Ref* sender)
{
auto gameScene = GameScene::createScene();
auto transition = TransitionFade::create(0.5f, gameScene);
Director::getInstance()->replaceScene(transition);
}参考资源
- 官方文档: https://docs.cocos.com/cocos2d-x/v4/manual/zh/
- Node 指南:
examples/core/node-scene.md - Director API:
api/director.md
Sprite(精灵)使用指南
官方文档
参考官方文档:https://docs.cocos.com/cocos2d-x/v4/manual/zh/
Instructions
Sprite 是 Cocos2d-x 中用于显示图片的基本节点类。Sprite 继承自 Node,可以显示纹理、支持动画、变换等操作。
Syntax
创建 Sprite
Sprite::create("filename.png")- 从图片文件创建Sprite::createWithTexture(texture)- 从纹理创建Sprite::createWithSpriteFrame(frame)- 从精灵帧创建Sprite::createWithSpriteFrameName("frame_name")- 从精灵帧名称创建Sprite::create("filename.png", Rect(x, y, width, height))- 从纹理区域创建
Example (从文件创建)
// 从图片文件创建
auto sprite = Sprite::create("player.png");
this->addChild(sprite);
// 指定位置
sprite->setPosition(Vec2(100, 100));Example (从纹理创建)
// 从纹理创建
auto texture = Director::getInstance()->getTextureCache()->addImage("player.png");
auto sprite = Sprite::createWithTexture(texture);
this->addChild(sprite);Example (从纹理矩形创建)
// 从纹理的某个区域创建(精灵表)
auto sprite = Sprite::create("spritesheet.png", Rect(0, 0, 32, 32));
this->addChild(sprite);Sprite 属性
setPosition(Vec2)- 设置位置setRotation(float)- 设置旋转角度setScale(float)- 设置缩放setAnchorPoint(Vec2)- 设置锚点setOpacity(GLubyte)- 设置透明度setColor(Color3B)- 设置颜色setFlippedX(bool)- 水平翻转setFlippedY(bool)- 垂直翻转
Example (位置和变换)
auto sprite = Sprite::create("player.png");
// 设置位置
sprite->setPosition(Vec2(400, 300));
// 设置锚点(默认 0.5, 0.5)
sprite->setAnchorPoint(Vec2(0.5f, 0.5f));
// 设置旋转
sprite->setRotation(45.0f);
// 设置缩放
sprite->setScale(2.0f); // 统一缩放
sprite->setScaleX(1.5f); // X 轴缩放
sprite->setScaleY(0.8f); // Y 轴缩放
// 设置透明度
sprite->setOpacity(128); // 0-255
// 设置颜色
sprite->setColor(Color3B::RED);翻转
// 水平翻转
sprite->setFlippedX(true);
// 垂直翻转
sprite->setFlippedY(true);Example (动画 Sprite - 使用 SpriteFrame)
// 创建 SpriteFrame 缓存
auto cache = SpriteFrameCache::getInstance();
cache->addSpriteFramesWithFile("spritesheet.plist", "spritesheet.png");
// 从 SpriteFrame 创建
auto sprite = Sprite::createWithSpriteFrameName("player_idle_01.png");
this->addChild(sprite);Example (帧动画)
Vector<SpriteFrame*> frames;
for (int i = 1; i <= 4; i++)
{
std::string frameName = StringUtils::format("player_walk_%02d.png", i);
auto frame = cache->getSpriteFrameByName(frameName);
frames.pushBack(frame);
}
auto animation = Animation::createWithSpriteFrames(frames, 0.1f);
auto animate = Animate::create(animation);
auto repeat = RepeatForever::create(animate);
sprite->runAction(repeat);Example (完整示例)
class GameScene : public Scene
{
public:
static Scene* createScene();
virtual bool init();
CREATE_FUNC(GameScene);
private:
Sprite* _player;
};
bool GameScene::init()
{
if (!Scene::init())
{
return false;
}
// 创建玩家精灵
_player = Sprite::create("player.png");
_player->setPosition(Vec2(400, 300));
_player->setAnchorPoint(Vec2(0.5f, 0.5f));
this->addChild(_player, 1);
// 添加动画
auto cache = SpriteFrameCache::getInstance();
cache->addSpriteFramesWithFile("player.plist", "player.png");
Vector<SpriteFrame*> frames;
for (int i = 1; i <= 4; i++)
{
auto frame = cache->getSpriteFrameByName(
StringUtils::format("player_walk_%02d.png", i));
frames.pushBack(frame);
}
auto animation = Animation::createWithSpriteFrames(frames, 0.1f);
auto animate = Animate::create(animation);
auto repeat = RepeatForever::create(animate);
_player->runAction(repeat);
return true;
}Example (性能优化 - 使用 SpriteBatchNode)
// 批量渲染相同纹理的精灵
auto batchNode = SpriteBatchNode::create("spritesheet.png", 100);
this->addChild(batchNode);
for (int i = 0; i < 50; i++)
{
auto sprite = Sprite::createWithTexture(batchNode->getTexture(),
Rect(i * 32, 0, 32, 32));
sprite->setPosition(Vec2(i * 50, 100));
batchNode->addChild(sprite);
}Example (纹理缓存)
// 预加载纹理
auto textureCache = Director::getInstance()->getTextureCache();
textureCache->addImage("player.png");
textureCache->addImage("enemy.png");
// 使用缓存的纹理
auto sprite = Sprite::create("player.png"); // 从缓存获取Reference
- 官方文档: https://docs.cocos.com/cocos2d-x/v4/manual/zh/
- Texture 指南:
examples/core/texture.md - Animation 指南:
examples/core/animation.md
Texture(纹理)使用指南
官方文档
参考官方文档:https://docs.cocos.com/cocos2d-x/v4/manual/zh/
Instructions
Texture 用于加载和管理图片资源。Cocos2d-x 使用 TextureCache 来缓存纹理,提高性能。
Syntax
纹理加载
- 使用
Director::getInstance()->getTextureCache()获取纹理缓存 addImage()方法加载并缓存纹理getTextureForKey()获取已缓存的纹理removeTexture()移除纹理removeAllTextures()清除所有纹理
纹理属性
getPixelsWide()- 获取纹理宽度getPixelsHigh()- 获取纹理高度getContentSize()- 获取内容大小getPixelFormat()- 获取像素格式
Example (加载纹理)
// 获取纹理缓存
auto textureCache = Director::getInstance()->getTextureCache();
// 加载纹理(会自动缓存)
auto texture = textureCache->addImage("player.png");
// 从纹理创建精灵
auto sprite = Sprite::createWithTexture(texture);
this->addChild(sprite);Example (异步加载纹理)
auto textureCache = Director::getInstance()->getTextureCache();
// 异步加载纹理
textureCache->addImageAsync("large_image.png", [this](Texture2D* texture) {
if (texture)
{
auto sprite = Sprite::createWithTexture(texture);
this->addChild(sprite);
log("Texture loaded successfully");
}
else
{
log("Failed to load texture");
}
});Example (纹理缓存管理)
auto textureCache = Director::getInstance()->getTextureCache();
// 预加载纹理
textureCache->addImage("player.png");
textureCache->addImage("enemy.png");
textureCache->addImage("background.png");
// 获取已缓存的纹理
auto texture = textureCache->getTextureForKey("player.png");
if (texture)
{
auto sprite = Sprite::createWithTexture(texture);
this->addChild(sprite);
}
// 移除单个纹理
textureCache->removeTexture(texture);
// 清除所有纹理(谨慎使用)
// textureCache->removeAllTextures();Example (纹理信息)
auto texture = Director::getInstance()->getTextureCache()->addImage("player.png");
// 获取纹理尺寸
int width = texture->getPixelsWide();
int height = texture->getPixelsHigh();
log("Texture size: %d x %d", width, height);
// 获取内容大小
Size contentSize = texture->getContentSize();
log("Content size: %.2f x %.2f", contentSize.width, contentSize.height);
// 获取像素格式
Texture2D::PixelFormat format = texture->getPixelFormat();
log("Pixel format: %d", format);Example (从纹理区域创建精灵)
// 加载纹理
auto texture = Director::getInstance()->getTextureCache()->addImage("spritesheet.png");
// 从纹理的某个区域创建精灵(精灵表)
Rect rect(0, 0, 32, 32); // x, y, width, height
auto sprite = Sprite::createWithTexture(texture, rect);
sprite->setPosition(Vec2(400, 300));
this->addChild(sprite);Example (纹理预加载)
class GameScene : public Scene
{
public:
static Scene* createScene();
virtual bool init();
CREATE_FUNC(GameScene);
private:
void preloadTextures();
int _loadedCount;
int _totalCount;
};
void GameScene::preloadTextures()
{
auto textureCache = Director::getInstance()->getTextureCache();
std::vector<std::string> textures = {
"player.png",
"enemy.png",
"background.png",
"bullet.png"
};
_totalCount = textures.size();
_loadedCount = 0;
for (const auto& texturePath : textures)
{
textureCache->addImageAsync(texturePath, [this](Texture2D* texture) {
_loadedCount++;
log("Loaded %d/%d textures", _loadedCount, _totalCount);
if (_loadedCount == _totalCount)
{
log("All textures loaded!");
// 开始游戏
}
});
}
}Example (内存管理)
// 在场景退出时清理不需要的纹理
void GameScene::onExit()
{
Scene::onExit();
// 移除游戏相关的纹理
auto textureCache = Director::getInstance()->getTextureCache();
textureCache->removeTextureForKey("player.png");
textureCache->removeTextureForKey("enemy.png");
// 注意:不要清除所有纹理,因为可能其他场景还在使用
}Reference
- 官方文档: https://docs.cocos.com/cocos2d-x/v4/manual/zh/
- Sprite 指南:
examples/core/sprite.md - 资源管理:
examples/core/resources.md
Cocos2d-x 引擎概述
官方文档
参考官方文档:https://docs.cocos.com/cocos2d-x/v4/manual/zh/
概述
Cocos2d-x 是一个开源的跨平台游戏开发框架,支持 C++ 开发,可以发布到多个平台。
引擎特性
跨平台支持
- 桌面平台: Windows, macOS, Linux
- 移动平台: Android, iOS
- Web平台: 通过 Cocos Creator 支持
核心功能
- 2D 图形渲染
- 精灵(Sprite)系统
- 动作(Action)系统
- 场景(Scene)管理
- 物理引擎集成(Box2D)
- 音频系统
- 粒子系统
- 动画系统
技术特点
- 基于 OpenGL ES 渲染
- 使用 C++ 开发
- CMake 构建系统
- 高性能渲染管线
- 支持自定义 Shader
版本信息
- 当前版本: Cocos2d-x v4
- 主要语言: C++
- 构建系统: CMake
- 渲染后端: OpenGL ES
适用场景
- 2D 游戏开发
- 跨平台游戏应用
- 教育类应用
- 工具类应用
参考资源
- 官方文档: https://docs.cocos.com/cocos2d-x/v4/manual/zh/
- GitHub: https://github.com/cocos2d/cocos2d-x
- 社区论坛: https://forum.cocos.org/
安装和配置指南
官方文档
参考官方文档:https://docs.cocos.com/cocos2d-x/v4/manual/zh/
概述
本指南介绍如何在不同平台上安装和配置 Cocos2d-x v4 开发环境。
系统要求
Windows
- Windows 7 或更高版本
- Visual Studio 2015 或更高版本(推荐 Visual Studio 2019)
- CMake 3.10 或更高版本
- Python 3.x
macOS
- macOS 10.13 或更高版本
- Xcode 10 或更高版本
- CMake 3.10 或更高版本
- Python 3.x
Linux
- Ubuntu 18.04 或更高版本(或其他现代 Linux 发行版)
- GCC 7 或更高版本
- CMake 3.10 或更高版本
- Python 3.x
安装步骤
1. 安装 CMake
Windows
# 下载并安装 CMake
# https://cmake.org/download/
# 或使用 Chocolatey
choco install cmakemacOS
# 使用 Homebrew
brew install cmakeLinux
# Ubuntu/Debian
sudo apt-get update
sudo apt-get install cmake
# 或使用 snap
sudo snap install cmake --classic2. 安装 Python
确保已安装 Python 3.x:
python3 --version3. 获取 Cocos2d-x
# 克隆仓库
git clone https://github.com/cocos2d/cocos2d-x.git
cd cocos2d-x
# 或下载 ZIP 文件
# https://github.com/cocos2d/cocos2d-x/releases4. 运行安装脚本
# 运行 setup.py
python setup.py
# 这会设置环境变量和创建 cocos 命令5. 验证安装
# 检查 cocos 命令
cocos --version
# 应该显示版本信息创建新项目
使用 cocos 命令
# 创建新项目
cocos new MyGame -p com.yourcompany.mygame -l cpp -d /path/to/projects
# 参数说明:
# -p: 包名(Package name)
# -l: 语言(cpp, lua, js)
# -d: 项目目录使用 CMake
# 进入项目目录
cd MyGame
# 创建构建目录
mkdir build
cd build
# 生成构建文件
cmake ..
# 编译
cmake --build .平台特定配置
Windows (Visual Studio)
# 生成 Visual Studio 解决方案
cmake .. -G "Visual Studio 16 2019" -A x64
# 打开 MyGame.sln 进行开发macOS (Xcode)
# 生成 Xcode 项目
cmake .. -G Xcode
# 打开 MyGame.xcodeproj 进行开发Linux
# 使用默认生成器(Makefile)
cmake ..
# 编译
make -j4Android
# 需要 Android SDK 和 NDK
# 设置环境变量
export ANDROID_NDK_ROOT=/path/to/android-ndk
export ANDROID_SDK_ROOT=/path/to/android-sdk
# 生成 Android 项目
cmake .. -DCMAKE_TOOLCHAIN_FILE=../platform/android/android.toolchain.cmake依赖管理
使用 Cocos2d-x 内置依赖
Cocos2d-x v4 使用 CMake 管理依赖,大部分依赖已包含在仓库中。
添加第三方库
# 在 CMakeLists.txt 中添加
find_package(SomeLibrary REQUIRED)
target_link_libraries(MyGame SomeLibrary)常见问题
CMake 找不到
确保 CMake 已添加到系统 PATH 环境变量中。
Python 版本问题
确保使用 Python 3.x,不是 Python 2.x。
编译错误
- 检查编译器版本是否符合要求
- 确保所有依赖已正确安装
- 查看 CMake 输出信息
参考资源
- 官方文档: https://docs.cocos.com/cocos2d-x/v4/manual/zh/
- 快速开始:
examples/getting-started/quick-start.md - 构建系统:
examples/tools/build-system.md
快速上手 - 创建第一个项目
官方文档
参考官方文档:https://docs.cocos.com/cocos2d-x/v4/manual/zh/
概述
本指南将帮助你创建第一个 Cocos2d-x v4 项目。
前置要求
- CMake 3.10 或更高版本
- C++ 编译器(Visual Studio, Xcode, GCC)
- Python 3.x(用于构建脚本)
创建项目
1. 克隆或下载 Cocos2d-x
git clone https://github.com/cocos2d/cocos2d-x.git
cd cocos2d-x2. 创建新项目
python setup.py
# 或使用 cocos 命令
cocos new MyGame -p com.yourcompany.mygame -l cpp -d /path/to/projects3. 构建项目
cd MyGame
mkdir build
cd build
cmake ..
cmake --build .第一个场景示例
#include "cocos2d.h"
USING_NS_CC;
class HelloWorld : public Scene
{
public:
static Scene* createScene();
virtual bool init();
CREATE_FUNC(HelloWorld);
};
Scene* HelloWorld::createScene()
{
return HelloWorld::create();
}
bool HelloWorld::init()
{
if (!Scene::init())
{
return false;
}
auto visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
// 创建一个标签
auto label = Label::createWithTTF("Hello Cocos2d-x", "fonts/Marker Felt.ttf", 24);
label->setPosition(Vec2(origin.x + visibleSize.width/2,
origin.y + visibleSize.height - label->getContentSize().height));
this->addChild(label, 1);
// 创建一个精灵
auto sprite = Sprite::create("HelloWorld.png");
if (sprite != nullptr)
{
sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
this->addChild(sprite, 0);
}
return true;
}运行项目
Windows
# 在 Visual Studio 中打开解决方案
# 或使用命令行
.\MyGame.exemacOS
open MyGame.appLinux
./MyGame基本概念
Node(节点)
- 所有显示对象的基础类
- 支持位置、旋转、缩放等变换
- 可以添加子节点形成树结构
Scene(场景)
- 场景图的根节点
- 通过 Director 管理场景切换
Sprite(精灵)
- 用于显示图片的节点
- 继承自 Node
Director(导演)
- 管理场景切换
- 管理渲染循环
- 获取窗口信息
参考资源
- 官方文档: https://docs.cocos.com/cocos2d-x/v4/manual/zh/
- 安装指南:
examples/getting-started/installation.md
This skill is based on the official Cocos2d-x v4 documentation.
Official Documentation: https://docs.cocos.com/cocos2d-x/v4/manual/zh/
Cocos2d-x is licensed under the MIT License.
For complete license terms, please refer to:
https://github.com/cocos2d/cocos2d-x/blob/v4/LICENSE