Skip to content

Multiple File Projects

matt-hayward edited this page Jan 5, 2021 · 3 revisions

If your project has multiple files, it's simple to effectively use the olc::PixelGameEngine.

Firstly, create an olcPixelGameEngine.cpp file in the same directory as the olcPixelGameEngine.h, with the following contents:

#define OLC_PGE_APPLICATION
#include "olcPixelGameEngine.h"

Once this file has been created, you only need to #include "olcPixelGameEngine.h" anywhere you want to reference the olc::PixelGameEngine.

Accessing olc::PixelGameEngine methods in other classes

There should only ever be one instance of the olc::PixelGameEngine in your game, which means it might not be immediately obvious how to use PGE methods in classes other than your main game class.

For example, if you have Game as your PGE-derived class, which has a Ball object as a member, it might look something like this:

class Game : public olc::PixelGameEngine
{
public:
    Game()
    {
        sAppName = "Ball Game";
    }

public:
    bool OnUserCreate() override
    {
        return true;
    }

    bool OnUserUpdate(float fElapsedTime) override
    {
        return true;
    }

protected:
    Ball ball;
}

And the Ball class might look something like...

class Ball
{
public:
    Ball()
    {

    }
    
    void DrawSelf()
    {

    }

public:
    olc::vf2d position = {0, 0};
}

It makes sense that you might want the Ball class to handle drawing itself. You'll probably want to use the FillCircle method from the olc::PixelGameEngine.

The recommended way to deal with this is to pass a pointer to your PGE-derived class into the Ball::DrawSelf() method. When we do this, the Ball class will look something like:

class Ball
{
public:
    Ball()
    {

    }

    void DrawSelf(olc::PixelGameEngine* pge)
    {
        pge->FillCircle(position, 3); // to define a 3px radius
    }

public:
    olc::vf2d position = {0, 0};
}

And the Game::OnUserUpdate() method will look something like:

bool OnUserUpdate(float fElapsedTime) override
{
    ball.DrawSelf(this); // `this` is a pointer to the instance of the `Game` class
    return true;
}

That's all there is to it! Just remember to #include "olcPixelGameEngine.h" in any file where you use an olc::PixelGameEngine method!