cocos2d-x 设置资源路径

2015年03月02日 11:49 0 点赞 0 评论 更新于 2025-11-21 16:32

问题发现

在开发过程中,偶然遇到这样的情况:项目在 Visual Studio(VS)调试时能够正常运行,但直接在生成目录执行可执行文件(exe)时,界面却显示黑屏。经过分析,问题出在资源文件加载方面,由于程序找不到图片资源,所以导致黑屏。

cocos2d-x 查找图片的机制

那么,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);

该函数的查找逻辑如下:

  1. 判断是否为绝对路径:首先判断传入的文件名是否已经是绝对路径,如果是,则直接返回该路径。
  2. 从缓存中查询:接着会从缓存中查询该资源的路径。之前已经加载过的资源,会以传入的关键字作为键进行路径缓存。
  3. 从文件名查找字典中匹配:如果在缓存中找不到,则会从文件名查找字典中进行匹配。
  4. 从查询路径数组中查找:最后会从查询路径数组中一个个进行匹配查找。此时会发现 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) 这个 win32 API 函数来获取当前的工作目录。当然,其他平台也会有对应平台的获取方式。

项目默认工作目录设置

打开项目属性管理器面板,在调试子面板中可以发现,通过 cocos2d-x 模板生成的项目,默认将工作目录设置为了 $(ProjectDir)..\Resources。所以在调试时,程序得到的工作目录便是这个 Resources 文件夹。

解决方案

最后,解决该问题的办法是将图片拷贝到可执行文件(exe)所在的文件目录下。因为 exe 所在的目录就是当前工作目录,这样程序就可以匹配到图片资源了。

作者信息

boke

boke

共发布了 3994 篇文章