SFML community forums
Help => Graphics => Topic started by: nbetcher on July 13, 2009, 11:36:09 pm
-
I am trying to get this bit of example code I found to work, but i'm not exactly sure how to use it.
class Missile
{
public :
static bool Init(const std::string& ImageFile)
{
return Image.LoadFromFile(ImageFile);
}
Missile()
{
Sprite.SetImage(Image); // every sprite uses the same unique image
}
private :
static sf::Image Image; // shared by every instance
sf::Sprite Sprite; // one per instance
};
I have that included in my code, but how would I create an object of that type? Its constructor calls Sprite.SetImage(Image), but the Init function is what sets the Image. I'm not sure how to set the Image with the Init function before the constructor is called. Or is there some other way I should be going about setting the Image for the object?
-
Static data members have to be defined outside the class (recommended in .cpp files), anyway - except integral constants.
Write in Missile.cpp:
sf::Image Missile::Image = Missile::InitImage();
Where Missile::InitImage is a static member function returning an sf::Image. Error checking gets more difficult like that, either you have to store a separate flag if initialization was successfull or you can use exceptions. Like this the sf::Image is guaranteed to be initialized before any Missile constructor call.
But static data can be dangerous because the initialization order in different modules in indeterminate. This can lead to problems if some static variables depend on others. Not very relevant for your example. Nevertheless, another possibility would be a singleton-like member function which returns a reference to a sf::Image. This function initializes the image at its first call. Inside the class, the image is always accessed via that function.
static sf::Image& GetImage()
{
static sf::Image Image;
return Image;
}
In my opinion, the best method is a separate class which manages the resources. Loading errors can easily be spotted and treated at a central place. If every class is responsible for its resources itsself, this can become confusing and unclear, especially when the project grows.
-
Just call Missile::Init("...") at the beginning of your program, before any missile is created. But this is just a simple example to illustrate what I say in the tutorial, don't copy-paste it ;)
-
Thanks guys, I appreciate the info! I have made a few 2 dimensional games with allegro, and now SFML. I have never had a solid method for managing images though. Maybe this is a topic better suited for a new thread, but does anyone have an example I could see that would illustrate a good way to manage a large amount of images to be used efficiently in a game? Thanks again.
-
There is (at least) one ImageManager on the wiki.