我正在尝试遵循一个关于制作 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/