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

Author Topic: Creating objects  (Read 1129 times)

0 Members and 1 Guest are viewing this topic.

aanthonyz

  • Newbie
  • *
  • Posts: 17
    • View Profile
Creating objects
« on: March 28, 2014, 12:28:21 am »
Hello, in efforts to clean up my code, I have decided to use files to store data. So far im working on loading the data in the first place. I have a file called Loading.txt and inside I have 3 lines:
times.ttf
music.ogg
Scene1.jpg
Images//NPC.jpg

Now this is my function so far:
sf::Font font;
sf::Music music;
void Load()
{
        std::ifstream loadfile("load.txt");
        std::getline(loadfile,filepath);
        font.loadFromFile(filepath);
        std::getline(loadfile,filepath);
        music.openFromFile(filepath);
        //etc...
        loadfile.close();

}
So far I have globally declared textures,font,music. etc, and i hard code in each one for loading.The part where im stuck at is, how should I approach implementing the Font, Music, and Textures. Would it be better to just hard code in a list of textures like I am currently doing, or is there a way to create them on the go? I dont know if im explaining it correctly but essentially is it possible to create a function that can read from the file and create a texture, font, or music object and then load it for use later down the line? At most I will have about 5 images on the screen at a time, so I was also thinking about just hard coding 5 textures and changing around each path and reloading when needed. Which do you guys recommend?

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6274
  • Thor Developer
    • View Profile
    • Bromeon
Re: Creating objects
« Reply #1 on: March 28, 2014, 12:50:12 am »
Forget global variables, forget hardcoding. Clean code is important, it will save you hours of tedious debugging.

You could have a look at some resource management systems, for example the one we wrote for the SFML book. It's very simple to use:
enum struct TextureId { Player, NPC, Terrain };

// initially, only once:
ResourceHolder<sf::Texture, TextureId> textures;
textures.load(TextureId::Player, "player.png");

// later:
sf::Texture& playerTexture = textures.get(TextureId::Player);
sf::Sprite playerSprite(playerTexture);

My extension library Thor contains a more sophisticated resource manager. I will also add a simple one in the near future.
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development: