Good evening,
I create a "tile mapped" game.
I have a Block class that allows me to create object blocks and a world class that allows me to manage my world (composed of object block).
Let me explain, in the constructor of World I fill a two-dimensional list of object Block. When they are created, Block's constructor assigns to the object a sprite to which it applies a texture. Then using a World method that I call in the Main, I draw Block objects contained in World (in the two-dimensional list) .. only I get the famous white square.
So the Sprite is there, it's the texture that no longer exists. I did some research and concluded that the texture was removed at the exit of the class in which it was created (which is why it works when I draw from the Block class). I also understood that I had to use dynamic allocations to solve this problem ... but I can not do it .. really .. it's been 3 weeks that I'm on it .. Can someone help me ?
Cordially.
Here is my code because I doubt that my explanation is sufficiently clear:
Block.hpp :
#ifndef Block_hpp
#define Block_hpp
#include <cstdio>
#include <string>
#include <SFML/Graphics.hpp>
class Block : public sf::Drawable
{
public:
Block();
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const
{
target.draw(block_sprite, states);
}
protected:
sf::Sprite block_sprite;
sf::Texture block_wood;
};
#endif
Block.cpp
#include "Block.hpp"
#include <cstdio>
#include <iostream>
#include <SFML/Graphics.hpp>
Block::Block()
{
if (!block_wood.loadFromFile("textures/planks_spruce.png"))
{
std::cout << "ok" << std::endl;
}
block_sprite.setTexture(block_wood);
block_sprite.setPosition(0, 0);
}
World.hpp :
#ifndef World_hpp
#define World_hpp
#include <cstdio>
#include <SFML/Graphics.hpp>
#include <string>
#include "Block.hpp"
class World
{
public:
World();
void render(sf::RenderWindow& window) const;
protected:
Block map[20][20];
};
#endif
World.cpp
#include "World.hpp"
#include "Block.hpp"
#include <SFML/Graphics.hpp>
#include <string>
#include <cstdio>
World::World()
{
Block block;
map[0][0] = block;
}
void World::render(sf::RenderWindow& window) const
{
window.draw(map[0][0]);
}
main.cpp
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include <string>
#include <iostream>
#include <cstdio>
#include "World.hpp"
int main(int, char const**)
{
const int w = 800;
const int h = 450;
sf::RenderWindow window;
sf::View view;
World world;
sf::Event event;
window.create(sf::VideoMode(w, h), "SFML window",sf::Style::Default);
window.setVerticalSyncEnabled(true);
while (window.isOpen())
{
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
view.reset(sf::FloatRect(0,0,w,h));
world.render(window);
window.display();
}
return EXIT_SUCCESS;
}