← Back to Blog

A simple 2D platformer game engine implemented in C++

This is an experimental C++ mini project creating a 2D platformer engine with a demo game, using the SFML library. This mini project used to be my assignment for a university subject called C11 and C++11 Programming. It handles minimal collision detection, control, movement, enemy interaction and level loading.

This video is obsolete, it still did not have animated sprite sheets. I might upload a newer version later. The graphics of the test scene is ad-hoc, because I focused on the structure in this case. My mini engine uses an architecture similar to in Unity3D, which relies on components. The game consists of a Scene which includes a number of GameObjects. Every GameObject has a Transform component and it may also have a number of other components.

class GameObject
{
    public:
        GameObject();
        GameObject(sf::RenderWindow& window);
        virtual void update();
        std::vector<std::shared_ptr<GameComponent>>& getComponents();
        void addComponent(std::shared_ptr<GameComponent> component);
        Transform& getTransform();
        void addWindow(sf::RenderWindow& window);
    protected:
        sf::RenderWindow* window;
    private:
        std::vector<std::shared_ptr<GameComponent>> components;
        std::shared_ptr<Transform> transform;
};


I derived classes SpriteRenderer and Collider from GameComponent. These can be added to our game objects in the scene, giving them a composite structure.
Each class that inherits from GameObject can override the Update method which is called before every draw, to update the state of the current object (e.g. control the Player). To make movements framerate independent, each translation is compensated with the static method getDeltaTime() multiplier of the GameTimer class.

getTransform().translate(MormotaConstants::PROJECTILE_VELOCITY * currDir
						 * GameTimer::getDeltaTime(), 0);


This returns the delay between the previous and current frame timestamp. At lower framerates this value is higher, at higher framerates it is lower, making translations consistent at different framerates. The reciprocal of the delta time is the FPS (frames per second).