SFML community forums

Help => Graphics => Topic started by: TheUselessGuy on November 14, 2020, 04:50:49 am

Title: Rendering multiple sprites at once (white square problem)
Post by: TheUselessGuy on November 14, 2020, 04:50:49 am
Hello today I was trying to create class that can create and render multiple objects. Unfortunately when I run my program I'm getting only white square.

main.cpp

#include "SFML/Graphics.hpp"

#include "Icons.hpp"

using namespace sf;
int main() {
        Icons icons;

        Event event;
        RenderWindow window(VideoMode(1280,720), "Test", Style::Close);

        while (window.isOpen()) {
                while (window.pollEvent(event)) {
                        switch (event.type) {
                        case Event::Closed: { window.close(); }
                        }
                }

                window.clear();
                window.draw(icons);
                window.display();
        }
        return EXIT_SUCCESS;
}

Icon.hpp

#pragma once
#include "SFML/Graphics.hpp"
#include <string>

class Icon{
public:
        sf::Texture texture;
        sf::Sprite sprite;
        Icon(std::string path) {
                texture.loadFromFile(path);
                sprite.setTexture(texture);
        }
};

Icons.hpp

#pragma once
#include "SFML/Graphics.hpp"
#include <vector>

#include "Icon.hpp"

class Icons : public sf::Drawable {
        std::vector<Icon> icons;
public:
        Icons() {
                icons.push_back(Icon("test.png"));
        }
private:
        virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const {
                for (const auto & icon : icons) {
                        target.draw(icon.sprite);
                }
        }
};

I'm out of ideas hope someone can help me. Btw I will appreciate any tips cuz I'm still learning how to program :-\
Title: Re: Rendering multiple sprites at once (white square problem)
Post by: Laurent on November 14, 2020, 09:21:01 am
Quote
I'm getting only white square
Have you tried to search "white square" on the forum or in the documentation/tutorials? This is a very common issue ;)
Title: Re: Rendering multiple sprites at once (white square problem)
Post by: Hapax on November 17, 2020, 01:25:56 pm
Remember that when you use a std::vector, they can be moved when resized. This means that any pointer to a vector's elements are no longer pointing to the correct thing.
When you set a texture, you are assigning a pointer to that texture.

If those elements are moved (along with their textures), you will need to re-assign the pointer (re-set the texture). Basically, add them all to the vector first, then set the textures. Or, reserve or pre-size the vector so that it doesn't get moved.