Game Engine Architecture
Build a minimal 2D game engine to apply all C++ concepts — classes, inheritance, templates, smart pointers, and STL containers. The Entity Component System (ECS) pattern is used by modern engines like Unity and Unreal.
45 min•By Priygop Team•Last updated: Feb 2026
Game Engine Code
Example
#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include <unordered_map>
using namespace std;
// Component base
struct Component {
virtual ~Component() = default;
virtual void update(float deltaTime) {}
};
// Position component
struct Transform : Component {
float x, y;
float rotation = 0.0f;
Transform(float x = 0, float y = 0) : x(x), y(y) {}
void update(float dt) override {
// Physics update would go here
}
};
// Velocity component
struct Velocity : Component {
float vx, vy;
Velocity(float vx = 0, float vy = 0) : vx(vx), vy(vy) {}
};
// Entity (game object)
class Entity {
string name;
unordered_map<string, unique_ptr<Component>> components;
public:
Entity(const string &name) : name(name) {}
template <typename T, typename... Args>
T &addComponent(Args&&... args) {
auto comp = make_unique<T>(forward<Args>(args)...);
T &ref = *comp;
components[typeid(T).name()] = move(comp);
return ref;
}
template <typename T>
T *getComponent() {
auto it = components.find(typeid(T).name());
if (it != components.end())
return static_cast<T*>(it->second.get());
return nullptr;
}
void update(float dt) {
// Apply velocity to transform
auto *transform = getComponent<Transform>();
auto *velocity = getComponent<Velocity>();
if (transform && velocity) {
transform->x += velocity->vx * dt;
transform->y += velocity->vy * dt;
}
}
const string &getName() const { return name; }
};
// Game loop
class Game {
vector<unique_ptr<Entity>> entities;
bool running = true;
public:
Entity &createEntity(const string &name) {
entities.push_back(make_unique<Entity>(name));
return *entities.back();
}
void update(float deltaTime) {
for (auto &entity : entities) {
entity->update(deltaTime);
}
}
void run() {
float dt = 1.0f / 60.0f; // 60 FPS
for (int frame = 0; frame < 5; frame++) {
update(dt);
// render() would go here
}
}
};
int main() {
Game game;
auto &player = game.createEntity("Player");
player.addComponent<Transform>(100.0f, 200.0f);
player.addComponent<Velocity>(50.0f, 0.0f);
auto &enemy = game.createEntity("Enemy");
enemy.addComponent<Transform>(400.0f, 200.0f);
enemy.addComponent<Velocity>(-30.0f, 10.0f);
game.run();
auto *pos = player.getComponent<Transform>();
if (pos) cout << "Player pos: (" << pos->x << ", " << pos->y << ")" << endl;
return 0;
}