如何解决尝试使用 SFML (C++) 从文件加载纹理时出错
我正在尝试使用 SFML 加载纹理并返回精灵,但纹理不会随我的路径加载。完整错误说:
dlist %>%
map2_dfr(names(dlist),~ c(.y,names(.x)) %>% set_names(~ letters[seq_along(.x)])) %>%
column_to_rownames("a")
b c d e
mtcars1 mpg cyl <NA> <NA>
mtcars2 mpg cyl disp <NA>
mtcars3 mpg cyl disp hp
所以我已经在我的 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]);
}
中加载初始精灵纹理
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
能否请您帮忙找出我遗漏了哪一部分。路径是正确的,我尝试了很多不同的方法:绝对路径,我检查过我的图像等等。
解决方法
我在调试过程中发现了 LoadTexture
函数实现中的一个问题。我的图像加载良好。问题在于使用 loadFromFile
从文件加载纹理(我没有加载纹理)。如果 loadFromFile
为真,它应该返回 hash
。只有当它没有加载时,它才应该返回错误。这是我的工作代码:
unsigned int SpriteFactory::LoadTexture(const std::string& texturePath)
{
unsigned int hash = std::hash<std::string>{}(texturePath);
if (textures.find(hash) == textures.end())
{
if (textures[hash].loadFromFile(texturePath));
{
return hash;
}
}
if (!textures[hash].loadFromFile(texturePath)) {
throw std::runtime_error("Could not find texture with path: " + texturePath);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。