Cocos2d-x 的资源路径

今天发现项目在VS调试时正常运行,直接在生成目录执行exe是黑屏

原因是资源文件加载的问题,找不到图片,所以黑屏了

那么cocos2d-x是怎么查找图片的呢

以下是关键部分源码:

获得完整路径

pathKey = CCFileUtils::sharedFileUtils()->fullPathForFilename(pathKey.c_str());
/** Returns the fullpath for a given filename.
     
     First it will try to get a new filename from the "filenameLookup" dictionary.
     If a new filename can't be found on the dictionary, it will use the original filename.
     Then it will try to obtain the full path of the filename using the CCFileUtils search rules: resolutions, and search paths.
     The file search is based on the array element order of search paths and resolution directories.
     
     For instance:

     .....

     @since v2.1
     */
    virtual std::string fullPathForFilename(const char* pszFileName);

首先判断如果已经是绝对路径则return

其次从缓存中查询(即之前已经加载过的资源,以你传递的关键字做key会做路径缓存)

如果还是找不到则从文件名查找字典中做匹配

就会从查询路径数组来一个个匹配查找

到了这里就会发现m_searchPathArray里已经存在了一个该项目目录下的Resource文件夹路径

那显然是在初始化的时候哪里设置了默认路径,继续追踪

这里CCFileUtils在初始化的时候会将默认资源路径String添加到数组中

bool CCFileUtils::init()
{
    m_searchPathArray.push_back(m_strDefaultResRootPath);
    m_searchResolutionsOrderArray.push_back("");
    return true;
}

继续查找m_strDefaultResRootPath是在哪里赋值

查找到子类的构造函数,例如我当前是win32项目则CCFileUtilsWin32.cpp中

bool CCFileUtilsWin32::init()
{
    _checkPath();
    m_strDefaultResRootPath = s_pszResourcePath;
    return CCFileUtils::init();
}
static void _checkPath()
{
    if (! s_pszResourcePath[0])
    {
        WCHAR  wszPath[MAX_PATH] = {0};
        int nNum = WideCharToMultiByte(CP_ACP, 0, wszPath,
            GetCurrentDirectoryW(sizeof(wszPath), wszPath),
            s_pszResourcePath, MAX_PATH, NULL, NULL);
        s_pszResourcePath[nNum] = '\\';
    }
}

这里因为是win32平台则就是通过

DWORD GetCurrentDirectoryW(DWORD nBufferLength, LPWSTR lpBuffer)

这个win32API函数来获取当前的工作目录了,当然其他平台也应该是对应平台的获取方式

然后,打开项目属性管理器面板,调试子面板中,发现这里通过cocos2d-x模板生成的项目,

默认将工作目录设置为了$(ProjectDir)..\Resources,所以通过调试时得到的工作目录便是这个Resources文件夹了。



 

那么最后,解决的办法就是将图片拷贝到exe所在的文件目录下,

因为exe所在的目录就是当前工作目录,则可以匹配上!

猜你喜欢

转载自rudolph.iteye.com/blog/1849203