簡體   English   中英

Sprite 在 SFML 中是白色方塊

[英]Sprite is white square in SFML

我創建了一個模板,該模板將保存指向任何類型資產的指針及其名為 ResourceHolder 的 ID,但是當我使用此模板實例中的紋理指針將紋理加載到精靈時,它是白色正方形。 這是我在 ResourceHolder.hpp 中的代碼:

#ifndef RESOURCEEHOLDER_H
#define RESOURCEHOLDER_H
#include "TexturesId.h"
#include "assert.h"
#include <SFML/Graphics.hpp>
#include <stdexcept>
#include <memory>
#include <string>
#include <map>
using namespace sf;
template<typename Resource,typename Identifier>

class ResourceHolder
{
    public:
        void load(Identifier id,const std::string &filename);
        Resource& get(Identifier id);
        const Resource& get(Identifier id) const;
    protected:

    private:
        std::map<Identifier,std::unique_ptr<Resource>> mResourceMap;
};

#endif // TEXTUREHOLDER_H

然后在 ResourceHolder.cpp 中編碼

#include "ResourceHolder.h"
using namespace sf;

template<typename Resource,typename Identifier>
void ResourceHolder<Resource,Identifier>::load(Identifier id,const std::string& filename)
{
    std::unique_ptr<Resource> resource(new Resource());
    if(!(resource->loadFromFile(filename)))
       {
           throw std::runtime_error("TextureHolder failed to load " + filename);
       }
    auto inserted=mResourceMap.insert(std::make_pair(id,std::move(resource)));
    assert(inserted.second);
}
template<typename Resource,typename Identifier>
Resource& ResourceHolder<Resource,Identifier>::get(Identifier id)
{
    auto found=mResourceMap.find(id);
    assert(found!=mResourceMap.end());
    return *found->second;
}
template<typename Resource,typename Identifier>
const Resource& ResourceHolder<Resource,Identifier>::get(Identifier id) const
{
    auto found=mResourceMap.find(id);
    assert(found!=mResourceMap.end());
    return *found->second;
}
template class ResourceHolder<Texture,Textures::ID>;

TextureId.h:

#ifndef TEXTURESID_H_INCLUDED
#define TEXTURESID_H_INCLUDED
namespace Textures
{
    enum ID{Landsape,Airplane,Missile};
}

#endif // TEXTURESID_H_INCLUDED

最后在 Game.cpp

Game::Game(int x,int y,std::string &Name)
:window(VideoMode(x,y),Name),texture(),
mPlayer()
{
    ResourceHolder<Texture,Textures::ID> th;
    th.load(Textures::ID::Airplane,"plane.png");
    Texture texture=th.get(Textures::ID::Airplane);
    mPlayer.setTexture(texture);
    mPlayer.setPosition(window.getSize().x/2,window.getSize().y/2);
}

有問題的代碼是 Game.cpp 中的代碼

Game::Game(int x,int y,std::string &Name)
:window(VideoMode(x,y),Name),texture(),
mPlayer()
{
    ResourceHolder<Texture,Textures::ID> th;
    th.load(Textures::ID::Airplane,"plane.png");
    Texture texture=th.get(Textures::ID::Airplane);
    mPlayer.setTexture(texture);
    mPlayer.setPosition(window.getSize().x/2,window.getSize().y/2);
}

ResourceHolderTexture只存在於Game構造函數的本地 scope 中。 一旦構造函數被執行, rhtexture都將用完 scope 並且精靈對紋理的引用無效,從而導致白色方塊問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM