Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Sprite is drawn as solid white  (Read 1872 times)

0 Members and 1 Guest are viewing this topic.

kepler0

  • Newbie
  • *
  • Posts: 23
    • View Profile
Sprite is drawn as solid white
« 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!
Zzz

UroboroStudio

  • Newbie
  • *
  • Posts: 25
    • View Profile
    • Email
Re: Sprite is drawn as solid white
« Reply #1 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

kepler0

  • Newbie
  • *
  • Posts: 23
    • View Profile
Re: Sprite is drawn as solid white
« Reply #2 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?
Zzz

UroboroStudio

  • Newbie
  • *
  • Posts: 25
    • View Profile
    • Email
Re: Sprite is drawn as solid white
« Reply #3 on: April 15, 2017, 02:53:33 pm »
As long is keep alive, yes.