[英]Why does SFML load a white square instead of a texture?
我正在上一个管理多个纹理的加载的类。 在完成之前,一切工作正常,但是当我使用全新的课程时,屏幕上只会出现一个白色正方形:
namespace Textures {
enum ID { Landscape, Airplane, Missile };
}
class ATextureHolder {
public:
void Load(Textures::ID id, const std::string& filename);
sf::Texture& Get(Textures::ID);
private:
std::map<Textures::ID, std::unique_ptr<sf::Texture>> texture_map;
};
void
ATextureHolder::Load(Textures::ID id, const std::string& filename) {
std::unique_ptr<sf::Texture> texture( new sf::Texture() );
texture->loadFromFile(filename.c_str());
this->texture_map.insert(std::make_pair(id, std::move(texture)));
}
sf::Texture&
ATextureHolder::Get(Textures::ID id) {
auto found = this->texture_map.find(id);
return *found->second;
}
AGame::AGame():
window( sf::VideoMode( 640, 480 ), "SFML Game" ),
player(), //player is an instance of sf::Sprite class
player_speed( 100.0 ),
time_per_frame( sf::seconds( 1.0 / 60.0 ) ) {
ATextureHolder textures;
textures.Load(Textures::Airplane, "Media/Textures/plane.png");
this->player.setTexture(textures.Get(Textures::Airplane));
this->player.setPosition(100.0, 100.0);
}
这个想法是用唯一的指针绑定存储在enum ID
纹理名称,而这些指针又指向实际的sf::Texture
对象。 因此,该类在Load()
方法中进行绑定,并且Get
方法应返回对这些纹理对象的引用。 但是出了点问题,我不知道那是什么。
我只是在这里猜测,但是...在AGame
构造函数中, textures
变量是一个局部变量,该变量超出范围并在构造函数返回时被破坏。 textures
或路线的这种破坏意味着它所包含的地图也被破坏,并且与之对应的unique_ptr
对象也将导致ATextureHolder::Get
返回的引用变得无效。
除非this->player.setTexture
通过值接受其参数并进行深层复制,否则纹理将无效并且对该对象的任何使用都将导致未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.