SFML community forums

Help => Graphics => Topic started by: jerryd on June 24, 2017, 05:17:49 am

Title: [SOLVED]One sprite for all my objects
Post by: jerryd on June 24, 2017, 05:17:49 am
SFML forum,
 
 I'm using SFML but this might be a C++ OOP question.

 I want to use a sprite from a class in all my objects:



class Sprite
{
public:
    Sprite() {};

    sf::Texture MySprite;
    sf::Sprite sprite;

    void Load_Sprite()
    {
        if(!MySprite.loadFromFile("C:/sprites/MySprite.png"))
        { cout << " Texture Loading Error" << endl; system("pause"); }
        sprite.setTexture(MySprite);
    }
};
 

 But I have go use one of the objects to load the sprite so now it
 belongs to that object.  I would like to make the sprite static so
 I only need one and use it in every object.

 Any suggestions on how to do that?
Jerryd
Title: Re: One sprite for all my objects
Post by: AFS on June 24, 2017, 06:34:07 am
Don't do that, just use one sprite per object. There's no problem in having many sprites, that's what they are for.

You should do that with your textures, though, because textures use more resources. Try to use only one texture for all your sprites, and to achieve that don't have a texture inside your class, but rather create your textures outside and just pass them to your "Load_Sprite()" method.

Something like this:

class Object {
       
    public:

        sf::Sprite mySprite;

        void load_sprite( sf::Texture & externalTexture ) {

            // It receives the texture externally as a parameter.
            // Don't forget to use the "&" symbol, meaning that
            // you are passing the texture "by reference".
            // (If you don't know what this is,
            // I strongly recommend reading about it).

            mySprite.setTexture( externalTexture );

        }

};

int main() {

    // You load your textures externally, NOT inside your class.

    sf::Texture myTexture;
    myTexture.loadFromFile("image.png");

    // You make instances of your class,
    // and you pass your textures as necessary.

    Object myObject;
    myObject.load_sprite( myTexture );

    Object anotherObject;
    anotherObject.load_sprite( myTexture );

    Object thirdObject;
    thirdObject.load_sprite( myTexture );

    ...

}
Title: Re: One sprite for all my objects
Post by: Paul on June 24, 2017, 12:28:53 pm
In the case of special requirements:
- you need any kind of texture manager
- manager can also hold sprite assigned to texture
- game objects can hold pointers to these sprites

The problem starts when you want to change the parameters of sprite, like scale. In such case you need individual sprites for each object, reset scale values or make sprite copies on-the-fly.