【发布时间】:2017-02-28 11:42:27
【问题描述】:
我的游戏世界中的每个对象都有一个精灵向量,可以直观地表示该对象。我的问题是我似乎无法在屏幕上正确绘制它们:
这是每个可绘制对象都继承自的可绘制对象:
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);
}
在这种情况下,地形精灵在运行时只是一个白盒。我认为这是因为 loadSprite 中的“纹理”和“精灵”变量在方法超出范围后被破坏。
我知道我可以通过在地形类中保存“纹理”和“精灵”来解决这个问题(而不是像现在这样在本地创建它们)。但这对我来说似乎没有必要,我不能将它们存储在向量 mySprites 和 myTextures 中吗?
【问题讨论】: