Reputation: 5709
I am trying to follow a slightly outdated tutorial on making a Tile Engine.
The problem is that the Texture I am trying to draw on screen, doesn't show up. I just get a black screen.
I've taken the most relevant parts of 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();
}
And here is the 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];
}
In the tutorial itself the Image
type was used but there was no Draw()
method for Image
so I made Texture
instead. Why won't the Texture
render on the screen?
Upvotes: 0
Views: 247
Reputation: 1708
The problem seems to be in:
void Engine::LoadTextures()
{
sf::Texture sprite;
sprite.loadFromFile("C:\\Users\\Vipar\\Pictures\\sprite1.png");
textureManager.AddTexture(sprite);
testTile = new Tile(textureManager.GetTexture(0));
}
You are creating a local sf::Texture
and passing that to TextureManager::AddTexture
. It's probably going out of scope at the end of the function, and is then no longer valid when you try to draw it. You fix this by using a smart pointer:
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));
}
And changing TextureManager
to use it:
void TextureManager::AddTexture(std::shared_ptr<sf::Texture> texture)
{
textureList.push_back(texture);
}
sf::Texture& TextureManager::GetTexture(int index)
{
return *textureList[index];
}
You'll also have to change textureList
to be an std::vector<std::shared_ptr<sf::Texture>
of course.
Upvotes: 1