0

我正在尝试遵循有关制作 Tile Engine 的稍微过时的教程。

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

我采用了 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在屏幕上渲染?

4

1 回答 1

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>

于 2013-05-23T16:33:09.113 回答