从精灵 SFML 向量中绘制

Drawing from a vector of sprites SFML

我的游戏世界中的每个对象都有一个精灵向量,可以直观地表示该对象。我的问题是我似乎无法在屏幕上正确绘制它们:

这是每个可绘制对象继承自的可绘制对象:

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 中的 "texture" 和 "sprite" var 在方法超出范围后被销毁。

我知道我可以通过在 terrain-class 中保存 "texture" 和 "sprite" 来解决这个问题(而不是像现在这样在本地创建它们)。但这对我来说似乎没有必要,我不能将它们存储在向量 mySprites 和 myTextures 中吗?

I think this is because the "texture" and "sprite" var in loadSprite gets destroyed after the method goes out of scope.

你是对的。 sf::Sprite stores a reference to sf::TextureloadSprite 只有在您 sprite.setTexture(myTextures.back()); 的情况下才能一次性工作。但是 std::vector 的元素将在您 push_back 时重新分配。为简单起见,我推荐 std::vector<std::shared_ptr<sf::Texture>>

更好的是,一次加载所有纹理,这样您就不会重复 并使用 ID 来引用它们。