基于C++的纯代码2D游戏开发框架设计
flowchart TD
A[游戏启动] --> B[初始化引擎]
B --> B1[创建窗口]
B --> B2[初始化渲染器]
B --> B3[加载资源]
B --> C[主游戏循环]
C --> D1[处理输入]
D1 -->|事件数据| D2[更新游戏状态]
D2 -->|实体变换数据| D3[物理检测]
D3 -->|碰撞数据| D4[逻辑响应]
D4 -->|渲染指令| D5[绘制场景]
D5 -->|帧缓冲| C
C --> E{退出条件?}
E -->|是| F[释放资源]
E -->|否| C
subgraph 核心模块
B1[Window模块]
B2[Renderer模块]
B3[ResourceManager]
end
subgraph ECS系统
D2[TransformSystem]
D3[PhysicsSystem]
D4[ScriptSystem]
D5[RenderSystem]
end
关键逻辑说明:
- 初始化阶段:
- 并行创建窗口、渲染器、加载资源
- 所有子系统通过引擎核心协调
- 游戏循环:
输入 → 逻辑更新 → 物理检测 → 碰撞响应 → 渲染 → (循环)
- 数据通过各系统管道式传递
- 每帧生成渲染指令集
- 模块交互:
- Window:接收OS事件 → 转译为游戏输入事件
- Renderer:消费场景图数据 → 输出帧缓冲
- ECS:各系统通过共享组件数据通信
- 资源流:
- 蓝色箭头:控制流
- 橙色箭头:数据流
- 虚线框:逻辑分组
核心架构设计
1. 基础模块
// Core.hpp - 框架核心
class GameEngine {
public:
virtual ~GameEngine() = default;
virtual void Initialize() = 0;
virtual void Update(float deltaTime) = 0;
virtual void Render() = 0;
virtual void Shutdown() = 0;
void Run();
};
2. 窗口管理
// Window.hpp - 跨平台窗口抽象
class Window {
public:
bool Create(const std::string& title, int width, int height);
void Destroy();
void ProcessEvents();
bool ShouldClose() const;
// 获取窗口尺寸
int GetWidth() const;
int GetHeight() const;
// 输入相关
bool IsKeyPressed(int keyCode) const;
// ...其他输入方法
};
3. 渲染系统
// Renderer.hpp - 2D渲染抽象
class Renderer {
public:
virtual ~Renderer() = default;
virtual void Clear() = 0;
virtual void Present() = 0;
// 2D绘图原语
virtual void DrawRectangle(float x, float y, float w, float h, Color color) = 0;
virtual void DrawSprite(Texture* texture, float x, float y) = 0;
virtual void DrawText(const std::string& text, float x, float y, Font* font, Color color) = 0;
// 变换
virtual void PushTransform(const Transform& transform) = 0;
virtual void PopTransform() = 0;
};
关键子系统实现
1. 资源管理
// ResourceManager.hpp
class ResourceManager {
public:
Texture* LoadTexture(const std::string& path);
Font* LoadFont(const std::string& path, int size);
Sound* LoadSound(const std::string& path);
void UnloadAll();
private:
std::unordered_map<std::string, std::unique_ptr<Texture>> m_textures;
std::unordered_map<std::string, std::unique_ptr<Font>> m_fonts;
// ...其他资源类型
};
2. 实体组件系统(ECS)
// ECS核心
class Entity {
public:
template<typename T>
void AddComponent(T&& component);
template<typename T>
T* GetComponent();
// ...其他ECS方法
};
class System {
public:
virtual void Update(float deltaTime) = 0;
};
class Scene {
public:
Entity* CreateEntity();
void AddSystem(std::unique_ptr<System> system);
void Update(float deltaTime);
private:
std::vector<std::unique_ptr<Entity>> m_entities;
std::vector<std::unique_ptr<System>> m_systems;
};
3. 输入系统
// InputSystem.hpp
class InputSystem : public System {
public:
void Update(float deltaTime) override;
bool IsKeyDown(KeyCode key) const;
bool IsMouseButtonDown(MouseButton button) const;
Vector2 GetMousePosition() const;
// 事件回调
void SetKeyCallback(std::function<void(KeyCode, bool)> callback);
private:
// 输入状态存储
};
框架使用示例
// 示例游戏实现
class MyGame : public GameEngine {
public:
void Initialize() override {
// 初始化窗口
m_window.Create("My 2D Game", 800, 600);
// 加载资源
m_playerTexture = m_resources.LoadTexture("player.png");
// 创建实体
auto player = m_scene.CreateEntity();
player->AddComponent<TransformComponent>(Vector2(400, 300));
player->AddComponent<SpriteComponent>(m_playerTexture);
player->AddComponent<PlayerControllerComponent>();
// 添加系统
m_scene.AddSystem(std::make_unique<RenderSystem>(&m_renderer));
m_scene.AddSystem(std::make_unique<PhysicsSystem>());
}
void Update(float deltaTime) override {
m_scene.Update(deltaTime);
}
void Render() override {
m_renderer.Clear();
// 场景渲染由RenderSystem处理
m_renderer.Present();
}
void Shutdown() override {
m_resources.UnloadAll();
m_window.Destroy();
}
private:
Window m_window;
Renderer m_renderer;
ResourceManager m_resources;
Scene m_scene;
Texture* m_playerTexture;
};
高级特性扩展
1. 粒子系统
class ParticleSystem : public System {
public:
void Update(float deltaTime) override;
void Emit(const ParticleEmitter& emitter);
private:
std::vector<Particle> m_particles;
};
// 使用示例
auto explosion = m_scene.CreateEntity();
explosion->AddComponent<ParticleEmitterComponent>(
/* 参数配置 */
);
2. 动画系统
class AnimationSystem : public System {
public:
void Update(float deltaTime) override;
};
struct AnimationComponent {
std::vector<Texture*> frames;
float frameDuration;
float currentTime;
int currentFrame;
bool looping;
};
3. 物理系统
class PhysicsSystem : public System {
public:
void Update(float deltaTime) override;
};
struct PhysicsComponent {
Vector2 velocity;
Vector2 acceleration;
float mass;
bool isStatic;
};
性能优化
- 对象池模式:对频繁创建销毁的对象(如粒子、子弹)使用对象池
- 批处理渲染:将相同材质的绘制调用合并
- 空间分区:使用四叉树或网格进行碰撞检测优化
- 内存管理:自定义分配器用于游戏对象
跨平台考虑
// 平台抽象层
namespace Platform {
// 文件系统
std::vector<uint8_t> ReadFile(const std::string& path);
// 时间
double GetCurrentTime();
// 图形API初始化
void InitGraphicsAPI();
}