Search code examples
c++cocos2d-x

Efficient way to store screen size, origin, and other global variables in Cocos2d-x?


I am building a 2d game using Cocos2d-x V3.x

I was wondering, what would be the best method to store the screen size variable, origin variable and others that can remain constant throughout the whole game?

For example:

Size windowSize = Director::getInstance()->getVisibleSize();
Vec2 windowOrigin = Director::getInstance()->getVisibleOrigin();

I believe these can be set as global variables.

What would be the most efficient way to do this?

Is the controversial singleton the best way?

Or should I just let each .cpp file have its own windowSize variables each time the scene is created?


Solution

  • there are many ways to do it, if you want to use one variable to use in all the scenes you can do it following way.

    //in header
    class BaseScene : public Scene
    {
    protected:
        Size windowSize;
        Vec2 windowOrigin;
    
    };
    
    //cpp file
    BaseScene::BaseScene() {
    
        windowSize = Director::getInstance()->getVisibleSize();
        windowOrigin = Director::getInstance()->getVisibleOrigin();
    }
    

    Now extend every scene from BaseScene class and directly use variable windowSize and windowOrigin