我的游戏世界中的每个对象都有一个精灵矢量,可以直观地表示该对象。我的问题是我似乎无法在屏幕上正确绘制它们:
这是每个drawable继承自的可绘制对象:
class Drawable {
private:
static vector<Drawable*> sprites;
protected:
vector<sf::Texture> myTextures;
vector<sf::Sprite> mySprites;
public:
Drawable();
static vector<Drawable*> getSprites();
void draw(sf::RenderWindow&) const;
};
及其.cpp:
vector<Drawable*> Drawable::drawables;
Drawable::Drawable() {
drawables.push_back(this);
}
vector<Drawable*> Drawable::getDrawables() {
return drawables;
}
void Drawable::draw(sf::RenderWindow& window) const {
for (auto sprite : mySprites) {
window.draw(sprite);
}
}
从drawable继承的对象示例:
class Terrain : public Drawable {
private:
void loadSprite(string);
public:
Terrain(string);
};
及其.cpp:
Terrain::Terrain(string fileName) {
loadSprite(fileName);
}
void Terrain::loadSprite(string fileName) {
sf::Texture texture;
texture.loadFromFile(fileName);
myTextures.push_back(texture);
sf::Sprite sprite;
sprite.setTexture(texture);
mySprites.push_back(sprite);
}
在这种情况下,地形精灵在运行时只是一个白盒子。我认为这是因为&#34;纹理&#34;和&#34;精灵&#34;方法超出范围后,loadSprite将被销毁。
我知道我可以通过保存&#34; texture&#34;来解决这个问题。和&#34;精灵&#34;在terrain类中(不是像现在这样在本地创建它们)。但这对我来说似乎没有必要,我不能将它们存储在载体mySprites和myTextures中吗?
答案 0 :(得分:3)
你是对的。我认为这是因为在方法超出范围后,loadSprite中的“texture”和“sprite”变量会被破坏。
sf::Sprite
stores a reference to sf::Texture
。 directory
只有loadSprite
才会工作一次。但sprite.setTexture(myTextures.back());
的元素将作为std::vector
重新分配。为简单起见,我建议使用push_back
。
更好的是,一次加载所有纹理,这样你就没有重复那些并使用ID来引用它们。