【发布时间】:2021-09-14 08:50:29
【问题描述】:
我正在尝试使用 SFML 加载纹理并返回精灵,但纹理不会随我的路径加载。完整的错误说:
libc++abi: terminating with uncaught exception of type std::runtime_error: Could not find texture with path: /Users/username/Library/Developer/Xcode/DerivedData/Test-eqrudqhtua/Build/Products/Debug/Test.app/Contents/Resources/tile.png
所以我已经在我的SpriteFactory.hpp中声明了
class SpriteFactory
{
//function when I load sprite for the first time
unsigned int LoadTexture(const std::string& texturePath);
//function to create a sprite
sf::Sprite GetSprite(unsigned int hash);
private:
//I’m using map to store textures
std::map<unsigned int, sf::Texture> textures;
};
这里是SpriteFactory.cpp中的实现
unsigned int SpriteFactory::LoadTexture(const std::string& texturePath)
{
//load texture if it's not loaded and return sprite
unsigned int hash = std::hash<std::string>{}(texturePath);
//if the hash of our texturePath exist in the textures
if (textures.find(hash) == textures.end())
{
// if it doesn't exist and reaches the end before texture
if (!textures[hash].loadFromFile(texturePath));
{
throw std::runtime_error("Could not find texture with path: " + texturePath);
}
}
return hash;
}
sf::Sprite SpriteFactory::GetSprite(unsigned int hash)
{
if (textures.find(hash) == textures.end())
{
throw std::runtime_error("Could not find texture with hash: " + hash);
}
return sf::Sprite(textures[hash]);
}
当我将上面的代码部分放在 cmets 中时,只会出现黑屏。
在我的main.cpp 中,我加载了初始精灵纹理
unsigned int tile = factory.LoadTexture(resourcePath() + "tile.png");
unsigned int tile_hl = factory.LoadTexture(resourcePath() + "tile.png");
然后我创建一个精灵表
Tile tilePart(factory.GetSprite(tile), factory.GetSprite(tile_hl),
sf::Vector2f(100.f, 100.f));
//draw it on screen
tilePart.Draw(window);
window.display();
我的Tile.cpp 部分实现在这里
Tile::Tile(sf::Sprite tile, sf::Sprite tile_hl, sf::Vector2f pos)
{
this->tile = tile;
this->tile_hl = tile_hl;
isHighlighted = (int)(pos.x /32) % 2 == 0;
//set position of a sprite
tile.setPosition(pos);
//reference points to address, tile I'm gonna to render
activeTile = isHighlighted ? &this->tile_hl : &this->tile;
}
Tile::Tile(const Tile& other)
{
tile = other.tile;
tile_hl = other.tile_hl;
isHighlighted = other.isHighlighted;
activeTile = isHighlighted ? &tile_hl : &tile;
}
void Tile::Draw(sf::RenderWindow& window)
{
if (isHighlighted)
{
activeTile = &this->tile_hl;
}
window.draw(*activeTile);
activeTile = &this->tile;
}
//whether we check highlights it will be set here
void Tile::SetHighlighted(bool flag)
{
// isHighlighted = flag;
}
请您帮忙找出我遗漏了哪一部分。路径是正确的,我尝试了很多不同的方法:绝对路径,我检查了我的图像等等。
【问题讨论】: