在SFML中不使用动态内存时,白色纹理代替实际纹理

时间:2018-06-07 13:09:53

标签: c++ graphics sfml

我有一个Armor类,用于存储要绘制到屏幕的纹理和精灵,如下所示:

Armor.h

class Armor 
{
public:
    Armor(const std::string& armorName);

    void draw(sf::RenderWindow& window);

    ~Armor();

private:
    sf::Texture armorTexture;
    sf::Sprite armorSprite;
    int numOfArmor;
};

Armor.cpp

#include "Armor.h"
Armor::Armor(const std::string& armorName)
{
    armorTexture.loadFromFile(armorName);
    armorSprite.setTexture(armorTexture);
    numOfArmor = 0;
}


void Armor::draw(sf::RenderWindow& window)
{
    window.draw(armorSprite);
}

Armor::~Armor()
{
}

我还有一个名为Application的对象,它在地图中存储Armor的实例,如下所示:

Application.h

class Application
{
public:
    Application();

    void start();

    ~Application();
private:
    sf::RenderWindow window;
    std::map<std::string, Armor> armorMap;
    std::map<std::string, Armor>::iterator armorIter;

};

Application.cpp

#include "Application.h"

Application::Application()
{
    window.create(sf::VideoMode(640, 480), "SFML Application", sf::Style::Close);
    window.setFramerateLimit(120);

    std::string armorName;
    std::ifstream file("Armors.txt");
    while (file >> armorName)
        armorMap.emplace(armorName, Armor(armorName + "Armor.png"));
    file.close();

    armorIter = armorMap.begin();
}

void Application::start()
{
    while (window.isOpen())
    {

        sf::Event evnt;
        while (window.pollEvent(evnt))
        {

            if (evnt.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        while (armorIter != armorMap.end())
        {
            armorIter->second.draw(window);
            armorIter++;
        }
        armorIter = armorMap.begin();
        window.display();
    }
}

Application::~Application()
{
}

每当我构造对象时,屏幕上会出现一个白色纹理,正如我所发现的那样,它被称为white texture problem。我很难过,因为我确定我的纹理没有被破坏,所以我决定将地图改为std::map<std::string, Armor*> armorMap,这解决了我所有的问题!为什么在地图中存储指向Armor类型对象的指针,但不是我最初的方式?

1 个答案:

答案 0 :(得分:0)

当您将盔甲对象存储到地图中时,您正在制作它的副本,纹理和精灵。

精灵将纹理存储为指向已销毁的原始纹理对象的指针(参见https://www.sfml-dev.org/documentation/2.5.0/classsf_1_1Sprite.php#a3729c88d88ac38c19317c18e87242560)。

无论如何,在地图中存储指针将为您提供更好的性能,因为您将避免不必要的纹理副本。你可能应该使用std::shared_ptr<Armour>而不是原始指针,除非你真的知道你在做什么。

相关问题