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

Author Topic: Sprites not displaying  (Read 220 times)

0 Members and 1 Guest are viewing this topic.

ranchu

  • Newbie
  • *
  • Posts: 4
    • View Profile
Sprites not displaying
« on: December 07, 2023, 05:07:44 pm »
Hello, I am new to sfml  and have been trying to display some sprites in my code, but they just will not display. Everytime i run the program it will display the window correctly, but it will not display anything else within it. I am aware that my code needs some serious re-arranging and optimisation, but my first concern is to get it running properly. Overall I'm just not sure what I'm doing wrong. 

kojack

  • Sr. Member
  • ****
  • Posts: 314
  • C++/C# game dev teacher.
    • View Profile
Re: Sprites not displaying
« Reply #1 on: December 07, 2023, 09:56:41 pm »
The issue is there are two versions of every sprite.
At the top you have a bunch of global sprites. These are the ones you are drawing.
But the code that loads the textures looks like this:
      if (background.loadFromFile("Assets/brick background2.jpg"))
      {
          sf::Sprite backgroundSprite(background);          
      }
It loads the texture, but then creates a temporary sprite called backgroundSprite and assigns the texture to it, instead of using the global backgroundSprite. (This is called variable shadowing, where two different variables have the same name and one hides the other)
At the closing brace in that code, the second backgroundSprite (the one with the texture) is deleted and only the original global one remains (without the texture).

Try this instead:
      if (background.loadFromFile("Assets/brick background2.jpg"))
      {
          backgroundSprite.setTexture(background);
      }
(Same for the other sprites)

ranchu

  • Newbie
  • *
  • Posts: 4
    • View Profile
Re: Sprites not displaying
« Reply #2 on: December 08, 2023, 12:33:46 pm »
I used your advice and the sprites are displaying correctly now, I wasn't aware of variable shadowing and just assumed that c++ wouldn't allow for such a thing, thanks.

 

anything