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

Author Topic: One Texture Shared to Multiple Sprites  (Read 5426 times)

0 Members and 1 Guest are viewing this topic.

Sparcsky

  • Newbie
  • *
  • Posts: 9
    • View Profile
One Texture Shared to Multiple Sprites
« on: May 26, 2017, 05:38:50 pm »
Is it possible to share only one texture into a different Sprites in order to minimize creating texture object?
or should I just make a Copy of it?



sf::Sprite enemy;
sf::Sprite player;

sf::Texture *texture;
texture = new Texture();

if (texture->loadFromFile("assets/player.png"))
player.setTexture(texture);

if (texture->loadFromFile("assets/enemy.png"))
enemy.setTexture(texture);

 

Arcade

  • Full Member
  • ***
  • Posts: 230
    • View Profile
Re: One Texture Shared to Multiple Sprites
« Reply #1 on: May 26, 2017, 06:05:08 pm »
You should just try out the code you posted and see if it works  :)

What you'll probably find, though, is that it won't do what you want. Sprites only hold a pointer to the texture. They don't internally make a copy of the texture themselves. There is only one texture in memory here, so if you change it then it will impact all of your sprites.

An alternative approach is to make one texture that contains all of your images (a "sprite sheet", PlayerAndEnemy.png). After setting the texture on your sprites, call setTextureRect() to only show the desired piece of the texture.

Sparcsky

  • Newbie
  • *
  • Posts: 9
    • View Profile
Re: One Texture Shared to Multiple Sprites
« Reply #2 on: May 26, 2017, 06:31:41 pm »
You should just try out the code you posted and see if it works  :)
I'm too lazy to start a new project and do set up all over again.   ;D

I'll just have to implement the alternative approach you have said and I think that's how it should be done anyway.

Turbine

  • Full Member
  • ***
  • Posts: 100
    • View Profile
Re: One Texture Shared to Multiple Sprites
« Reply #3 on: May 30, 2017, 05:09:40 pm »
Texture is a light object, any references will be just that. There's no need to reuse the same texture object. xD

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11030
    • View Profile
    • development blog
    • Email
Re: One Texture Shared to Multiple Sprites
« Reply #4 on: May 31, 2017, 02:06:08 pm »
A texture object is not light object.

A texture object needs to stay alive as long as you want to use the underlying texture data. Because a sprite just holds a reference to the texture object, so if you load a different image, the sprite will display the new image.

However using multiple instances of textureis not a bad or complicated thing.
To nicely handle textures, I do recommend to use a texture holder as Thor provides or similar.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/