Search code examples
c++cocos2d-xcocos2d-x-3.0

cocos2d-x 3.0 - Create sprite by relative path


How can I create a sprite with relative path? I mean I have several folder in Resources directory such as:

  • sd
  • hd
  • ....

One of this directories is set as the place where resources should be looked up :

std::vector<std::string> resDirOrders;
 if (device is hd)
      resDirOrders.push_back("hd")
FileUtils::getInstance()->setSearchResolutionsOrder(resDirOrders);

Now in each of above mentioned directories I have lots of other directories such as:

  • intro_popup
  • outro_popup
  • main_menu
  • top_bar
  • ingame
  • ....

In these directories I place the images. And the names of images can collide, as far as I can have coin.png in main_menu, in top_bar in ingame which are different images. Theretofore, I want to be able to create a sprite like this:

Sprite::create("ingame/coin.png");
Sprite::create("top_bar/coin.png");

But it does not work. It just does not find the file coin.png.

How I should solve this issue? I am on Windows with cocos2d-x 3.0, but it should be handled on iOS and Android too.


Solution

  • The folder structure must be like this :

    Res/
    ----hd/
    ----sd/
    ----ingame/
        ----hd/
        ----sd/
    ----top_bar/
        ----hd/
        ----sd/
    

    You should add the Res folder to the project, and make sure that "Create folder references for any added folders" is checked.

    Set the search path and search resolution order:

    Size screenSize = Director::getInstance()->getOpenGLView()->getFrameSize();
    
    std::vector<std::string> resDirOrders;
    
    std::vector<std::string> searchPaths = FileUtils::getInstance()->getSearchPaths();
    searchPaths.insert(searchPaths.begin(), "Res");
    FileUtils::getInstance()->setSearchPaths(searchPaths);
    
    if (screenSize.width > 1024) {
        resDirOrders.push_back("hd");
    }
    else{
        resDirOrders.push_back("sd");
    }
    
    FileUtils::getInstance()->setSearchResolutionsOrder(resDirOrders);
    

    Then you can create the sprite with Sprite::create("ingame/coin.png");