(SFML 2.4.2) How to apply one Texture to multiple Sprites

Hayk Khulyan

As the title says, I would like to apply one Texture object to multiples Sprites. The following is the main function where 10 Creature objects are created:

int main() {
    ...

    // creates a Creature vector and fills it with 10 Creature objects
    std::vector<Creature> creatureList;
    for (int i = 0; i < 10; i++) {
        creatureList.emplace_back();
    }

    ...
}

The following is the Creature header file:

class Creature {
public:
    Creature();
    ...
private:
    ...
    sf::Texture bodyTexture;
    sf::Sprite body;
};

And finally, the following is the source file:

Creature::Creature() {
    ...
    bodyTexture.loadFromFile("square.png");
    ...
    body.setColor(sf::Color(rgbDistribution(mt), rgbDistribution(mt), 
    rgbDistribution(mt)));
    body.setTexture(bodyTexture);
}

The problem with this code is that it gives only the most recently created Creature object the actual texture, leading me to believe it keeps changing "possession" of the bodyTexture each time body.setTexture(bodyTexture); is called.

What am I missing here? I've tried experimenting with throwing around various pointers and other stuff, but to no avail.

Hayk Khulyan

Found an answer: I simply had to pass the texture as a reference so the "owner" of the texture wouldn't change each time I called body.setTexture(bodyTexture);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive