Rafal Fuchs
Rafal Fuchs

Reputation: 21

Why that code don't draw sprites C++ SFML

I wanted to draw sprites on screen having only information about it in my struct and next draw text on it

Information are good X and Y scale=1 Path is good and point to graphic position and rotation =0;

int free have a good number

But Text works so i don't know why Sprite don't

I tried commenting code with drawing and making text don't work

struct ObjectInfo
{
    float Xpoz,Ypoz;
    std::string TexPath;
    float Xscale,Yscale;
    float Rotation;

};
ObjectInfo OI[1000];

int free;

void Draw()
{
    for(int i=0;i<free;i++)
    {
        sf::Texture t;
        t.loadFromFile(OI[i].TexPath);
        sf::Sprite s;
        s.setTexture(t);
        s.setPosition(OI[i].Xpoz,OI[i].Ypoz);
        s.setScale(OI[i].Xpoz,OI[i].Ypoz);
        s.setRotation(OI[i].Rotation);

        okno.draw(s);

        sf::Text text;
        text.setFont(font);
        text.setCharacterSize(48);
        text.setColor(sf::Color::Black);
        text.setPosition(s.getPosition());
        text.setString(IntToString(i));

        okno.draw(text);
    }
}

I expected that sprites and Text display but only text display

Upvotes: 2

Views: 349

Answers (1)

Yuriy
Yuriy

Reputation: 26

When you call s.setTexture(t) sprite s remembers texture t by pointer/reference. So, when your code exit from for loop sf::Texture t is destroyed (C++ destroy scope variables when exiting some scope) and pointer/reference in sprite class points to deleted memory locations, which cause SFML to have error while drawing your sprites. The solution to this problem is the global array for textures which you use. I also recommend adding the global array for sf::Sprites, because it makes your code safer. Here is how it may be implemented:

//In the global scope
sf::Texture textures[1000];
sf::Sprite sprites[1000];
//void draw() new for loop
for(int i=0;i<free;i++)
{
    textures[i].loadFromFile(OI[i].texPath);
    sprites[i].setTexture(s);
    //Set other parameters
    okno.draw(s);
    sf::Text text;
    text.setFont(font);
    text.setCharacterSize(48);
    text.setColor(sf::Color::Black);
    text.setPosition(s.getPosition());
    text.setString(IntToString(i));

    okno.draw(text);
}

By the way, there are some more improvements to your code. Texture loading operation is a heavy operation, so if paths to textures are immutable, I will recommend you adding some method for loading them at once. Also, creating text class may be a heavy operation, so it is good to add global array of sf::Text classes you use

Upvotes: 1

Related Questions