SFML community forums

Help => Graphics => Topic started by: kepler0 on April 15, 2017, 02:21:38 pm

Title: Sprite is drawn as solid white
Post by: kepler0 on April 15, 2017, 02:21:38 pm
Hello!

I've come a across an issue which I cannot seem to understand.
So I'm creating a header file to handle all my tile creation, which can be passed onto main.cpp to be drawn (sort of). But I'm having some trouble.

tiles.h
#pragma once

#include <SFML/Graphics.hpp>

sf::Sprite createWallSide(sf::Vector2f position,int side) {
        // Create texture and load image
        sf::Texture wallSide_texture;
        wallSide_texture.loadFromFile("Tiles/Walls/wallSide.png");
        wallSide_texture.setSmooth(false);

        // Create sprite and set texture
        sf::Sprite wallSide;
        wallSide.setTexture(wallSide_texture);
        wallSide.setPosition(position);
        wallSide.setRotation(90);
        switch (side) {
                case 0:
                        wallSide.setScale(5, 5);
                        break;
                case 1:
                        wallSide.setScale(-5, 5);
                        break;
        };
        // Return sprite
        return wallSide;
}

main.cpp
Only the relevant parts:
Variable declaration
sf::Sprite wall = createWallSide(sf::Vector2f(100, 100), 0);
Variable later being drawn
window.draw(wall);

Now I first suspected it was the image itself, so instead of making it a transparent background, I made it a black background, but it made no difference. So then I thought it was smoothing, and since the image is small, it was maybe being blurred to hell, but setSmooth made no difference.

Any help is appreciated!
Title: Re: Sprite is drawn as solid white
Post by: UroboroStudio on April 15, 2017, 02:31:31 pm
The problem is that you are creating the sf::Texture inside the createWallSide() function, so when the function ends, the texture is destroyed and the sprite returned have a pointer to an invalid texture.

You must keep the texture alive as long your sprites are using them. One solution to this is to create the texture in main.cpp.

Read this tutorial for more info https://www.sfml-dev.org/tutorials/2.4/graphics-sprite.php#the-white-square-problem (https://www.sfml-dev.org/tutorials/2.4/graphics-sprite.php#the-white-square-problem)
Title: Re: Sprite is drawn as solid white
Post by: kepler0 on April 15, 2017, 02:43:44 pm
Ah, I understand now. But if I for example stored it in a variable in tiles.cpp, and referenced to that from main.cpp, it would work, right?
Title: Re: Sprite is drawn as solid white
Post by: UroboroStudio on April 15, 2017, 02:53:33 pm
As long is keep alive, yes.