The white square problem is usually caused by some unintentional copy of the texture or accidental memory mismanagement. The usual paradigm in SFML is to keep textures external from the drawable classes which use them, so that copying the drawable won't make a copy of the texture. Often some sort of
resource management is used. SFML also provides an interface for creating custom drawables such as a Player class in a consistent way by inheriting
sf::Transformable and
sf::Drawable, which would look something like this:
class Player final : public sf::Transformable, public sf::Drawable
{
public:
void setTexture(const sf::Texture& texture)
{
m_sprite.setTexture(texture);
}
void setTextureRect(sf::IntRect rect)
{
m_sprite.setTextureRect(rect);
}
private:
sf::Sprite m_sprite;
void draw(sf::RenderTarget& target, sf::RenderStates states) const override
{
states.transform *= getTransform();
target.draw(m_sprite, states);
}
};
How this works is explained in the
documentation. Note that the class does not have a texture member. Rather, you would use it like this:
int main()
{
sf::Texture playerTexture;
playerTexture.loadFromFile("test.png");
Player player;
player.setTexture(playerTexture);
player.setTextureRect({ 2,2,100,100 });
sf::RenderWindow window(sf::VideoMode(800, 600), "My window");
sf::Clock frameClock;
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
}
float elapsed = frameClock.restart().asSeconds();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
player.move(-20.f * elapsed, 0.f);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
player.move(20.f * elapsed, 0.f);
}
window.clear(sf::Color::Black);
window.draw(player);
window.display();
}
return 0;
}
With the texture in its own scope (either as in the example or stored in a resource manager) copying drawable classes like Player can be done safely without accidentally copying any textures they use. There is also no need to use new/delete in this example, everything is fine on the stack. And even if there were a reason to use the heap
smart pointers would be the way to go.