Alright, so I'm using the Allegro gaming library in C++ to make a little space shooter game, and need some help with the bullets.
in semi-psuedocode its works like this:
now, all this works fine, but the problem is that when a laser is off the screen, it's still taking up memory, and space in the vector object (and therefore adding to the length of the draw method). Ideally, I would like to remove the laser object from the vector, and then destruct (if destruct isn't what I'm looking for, I just want to delete the object) it.
I'll go try and answer some questions now so I don't feel leechy, thanks.
Why not just give the laser a 'time to live', and when it has expired, remove and destruct it?
Joined: Jul 19, 2011
Stephan van Hulst wrote:Why not just give the laser a 'time to live', and when it has expired, remove and destruct it?
Because then it would still be in the vector wouldn't it? and since every object in the vector adds another iteration to the for loop. Also, I'm not really sure how to use destructors, I couldn't find any good guides. Can you just call ~lasers() (which is blank) and be done with it?
I take it you're using an iterator to go over all the elements when you want to draw them or update their positions or whatever. Before you do, inspect their time to live field, and if the laser has expired, call the erase method on the container, and then destruct the laser itself. You should probably use a list<laser> instead of a vector<laser>, because a list should be faster at removing elements at some random position.
The loop would look something like this:
Note that I've hardly ever coded in C++ myself, so I can't guarantee this will work.
I figured the destructor is not necessary, because C++ automatically destroys objects in certain circumstances, I believe. I changed the code accordingly.