纹理没有在屏幕上绘制

时间:2013-05-23 16:11:33

标签: c++ sfml

我正在尝试关注制作平铺引擎的稍微过时的教程。

问题是我试图在屏幕上绘制的纹理没有显示出来。我只是一个黑屏。

我采用了Engine.cpp最相关的部分:

bool Engine::Init()
{
    LoadTextures();
    window = new sf::RenderWindow(sf::VideoMode(800,600,32), "RPG");
    if(!window)
        return false;

    return true;
}

void Engine::LoadTextures()
{
    sf::Texture sprite;
    sprite.loadFromFile("C:\\Users\\Vipar\\Pictures\\sprite1.png");
    textureManager.AddTexture(sprite);
    testTile = new Tile(textureManager.GetTexture(0));
}

void Engine::RenderFrame()
{
    window->clear();
    testTile->Draw(0,0,window);
    window->display();
}

void Engine::MainLoop()
{
    //Loop until our window is closed
    while(window->isOpen())
    {
        ProcessInput();
        Update();
        RenderFrame();
    }
}

void Engine::Go()
{
    if(!Init())
        throw "Could not initialize Engine";
    MainLoop();
}

这是TextureManager.cpp

#include "TextureManager.h"
#include <vector>
#include <SFML\Graphics.hpp>

TextureManager::TextureManager()
{

}

TextureManager::~TextureManager()
{

}

void TextureManager::AddTexture(sf::Texture& texture)
{
    textureList.push_back(texture);
}

sf::Texture& TextureManager::GetTexture(int index)
{
    return textureList[index];
}

在教程本身中使用了Image类型,但Draw()没有Image方法,所以我改为Texture。为什么Texture不会在屏幕上呈现?

1 个答案:

答案 0 :(得分:1)

问题似乎在:

void Engine::LoadTextures()
{
    sf::Texture sprite;
    sprite.loadFromFile("C:\\Users\\Vipar\\Pictures\\sprite1.png");
    textureManager.AddTexture(sprite);
    testTile = new Tile(textureManager.GetTexture(0));
}

您正在创建本地sf::Texture并将其传递给TextureManager::AddTexture。它可能在函数结束时超出范围,然后在您尝试绘制它时不再有效。您可以使用智能指针解决此问题:

void Engine::LoadTextures()
{
    textureManager.AddTexture(std::shared_ptr<sf::Texture>(
        new sf::Texture("C:\\Users\\Vipar\\Pictures\\sprite1.png")));

    testTile = new Tile(textureManager.GetTexture(0));
}

更改TextureManager以使用它:

void TextureManager::AddTexture(std::shared_ptr<sf::Texture> texture)
{
    textureList.push_back(texture);
}

sf::Texture& TextureManager::GetTexture(int index)
{
    return *textureList[index];
}

当然,您还必须将textureList更改为std::vector<std::shared_ptr<sf::Texture>