c++ - 纹理未在屏幕上绘制

标签 c++ sfml

我正在尝试遵循一个关于制作 Tile 引擎的稍微过时的教程。

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

我选取了 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 类型,但是 Image 没有 Draw() 方法,所以我制作了 Texture 代替。为什么 Texture 不会在屏幕上呈现?

最佳答案

问题似乎出在:

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>当然。

关于c++ - 纹理未在屏幕上绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16718900/

相关文章:

c++ - 在 Qt 中绘制在标签的顶部,而不是在它的后面

c++ - 为什么不能在main.cpp中编写QWidget类?

c++ - C++ 类 : undefined reference 中的静态常量

c++ - fatal error : SFML/System. 找不到 hpp 文件

c++ - SFML Project microsoft visual express 2010 到 2012 兼容性问题

c++ - SFML C++ 我错误地使用了增量时间......正确的方法是什么

c++ - 将类型包装在结构中会导致额外的填充吗?

c++ - 使用 Conan 安装 boost 时出现身份验证错误

c++ - RenderWindow.display() 导致 sfml 崩溃

c++ - SFML 2.1 "setFont"未处理的异常