我使用SDL构建了一个空间入侵者克隆,并使用MSVC11编译。该代码加载了4个单独的PNG文件和一个TTF字体,用于渲染。给定绝对文件路径例如“C:/spaceinvader.png”时,程序可以正常工作。
我尝试将其更改为相对文件路径,即“./res/spaceinvader.png
然后程序在发布模式下编译,并将其放在自己的文件夹中。
目录结构:
game\game.exe
game\(all the required SDL dlls)
game\res\image1.png (and the other 3 images)
game\res\font.ttf
当你尝试运行游戏时,最奇怪的事情发生了。第一次尝试运行时,程序控制台将加载,SDL窗口打开,然后崩溃到桌面。 (我确保main()中没有过早的返回码)。然而,随后的所有时间,程序加载并工作,尽管其中一个精灵没有显示在屏幕上。控制台中出现的唯一错误与两个具有错误sRGB配置文件的PNG文件有关。
如果将整个文件夹移动到其他位置,则程序第一次不会再次加载,但随后会加载
所以我的问题是
1)为什么程序第一次没有加载,但随后? 2)当文件全部相同(在photoshop中创建)并且加载它们的代码相同时,为什么只有一个sprite才会显示失败?
(道歉,此处不包含任何代码,因为我觉得这不是编码问题 - 很高兴根据要求粘贴特定的代码段)
谢谢! ķ
编辑:
图像加载代码(从here:
中填充的loadTexture函数SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren)
{
SDL_Texture *texture = IMG_LoadTexture(ren, file.c_str());
log_CheckSDLPointer(std::cout, texture, "LoadTexture");
return texture;
}
int Gamestate::initialiseSprites(SDL_Renderer *Renderer)
{
enemytexture = loadTexture("./res/invader.png", Renderer);
if (enemytexture == nullptr) {return 1;}
playertexture = loadTexture("./res/player.png", Renderer);
if (playertexture == nullptr) {return 1;}
missiletexture = loadTexture("./res/bullet.png", Renderer);
if (missiletexture == nullptr) {return 1;}
background = loadTexture("./res/background.png", Renderer);
if (background == nullptr) {return 1;}
return 0;
}
在main中调用此函数:
if (Active_Gamestate.initialiseSprites(mainRenderer) != 0)
{
return 1; //quit game if sprites could not be initialised
}
答案 0 :(得分:0)
感谢所有帮助。我想我已经知道发生了什么。如果图像加载代码更改为以下内容:
char executablePath[FILENAME_MAX];
std::stringstream invaderpathstream;
invaderpathstream << executablePath << "/res/invader.png";
std::string invaderpath = invaderpathstream.str();
enemytexture = loadTexture(invaderpath, Renderer);
if (enemytexture == nullptr)
{return 1;}
问题消失了。也许问题在于相对路径(至少在我的系统上),也许在第一次运行程序之后,操作系统会以某种方式找到所需的文件,这就是为什么它在后续运行中顺利运行的原因?
ķ