SFML community forums
Help => General => Topic started by: cristi121 on April 15, 2011, 01:13:21 pm
-
Hi!
I've run into yet another problem with my Pong game.
I'm trying to store my Widgets in a STL vector, but the image always changes. Here's an example:
#include <iostream>
#include <vector>
#include <SFML/Graphics.hpp>
using namespace std;
class Widget
{
public:
void setImage (string file)
{
image.LoadFromFile (file);
sprite.SetImage (image);
}
void draw (sf::RenderWindow &app)
{
app.Draw (sprite);
}
private:
sf::Sprite sprite;
sf::Image image;
};
int main()
{
sf::RenderWindow app;
app.Create (sf::VideoMode (800,600,32), "ex");
vector <Widget> widgets;
Widget wid;
wid.setImage ("play.png");
widgets.push_back (wid); //now there should be a copy of wid in the vector
wid.setImage ("exit.png"); // why does this interfere with the content of the vector?
while (true)
{widgets[0].draw(app); app.Display(); } //this displays exit.png
return 0;
}
The push_back function doesn't seem to be copying the Image correctly. I tried the same example using an integer instead of a Widget objects and the variables are copied and stored correctly.
Thanks.
-
I've just found my answer.
The only thing that you must keep in mind is that some operations (such as adding an element) may move all the vector elements elsewhere in memory, invalidating all the sprites that previously pointed to them.
I should have looked more before asking. :oops:
But now, the problem is, how do I print those images correctly?
Or, does anybody know a better way to do this? ( several widgets in a container )
Edit:
I've figured out a solution:
void draw (sf::RenderWindow &app)
{
sprite.SetImage (image);
app.Draw (sprite);
}
[/quote]
-
If you're trying to manage/store your drawbles (Sprites, text, etc), I would suggest you to read this:
[SFML Wiki]LAYER (http://www.sfml-dev.org/wiki/fr/sources/layer)
It's in french but even if you can't read it, the code is very simple to understand and use :wink:
-
Thanks for the tip!
Luckily, I've been studying french in school since 5th grade. :)
-
I think your problem is:
You have to do:
wid.setImage ("exit.png");
BEFORE pushing wid to the widgets vector and NOT afterwards.
-
you could use a linked list
I had a similar problem in my particle system when it was pushing all the particles onto a vector, they would sometimes fall out of scope, then back when the array resized itself, i used std's linked list structure and have had no problems with images