Page 1 of 1

[SOLVED]Destroying objects help

Posted: Fri Jun 05, 2009 12:45 pm
by Panama
Hi people, this is my first thread here as I have just signed up so it is nice to meet you all :)

I am currently in the process off making a 2D side scrolling shooter (like Metal Slug.... just not nearly as good) game with C++ and DirectX. I have my window created, my player class and bullet class. My problem is that after about a minute of firing bullets the game gets very laggy indeed. I would really appreciate it if someone could explain to me how I go about deleting the bullets that are no longer in the window. Currently I am using vectors to store all my bullet objects however at the moment I have no way to destroying them.

Any and all help is appreciated

Your friend
Panama

Re: Destroying objects help

Posted: Fri Jun 05, 2009 1:11 pm
by programmerinprogress
Have you considered using a static array, and then writing some methods to maintain the list, making the bullets visible/invisible rather than constantly re-allocating the objects over and over.

In my game Alien Invasion, I used a rather large static array, if you don't believe the kind of speed improvement, you might like to check it out here: http://www.programmerinprogress.com/USE ... %201_1.zip

Also, welcome to the forum, I hope my answer helped ;)

PS: personally I wouldn't recommend dynamic allocation unless you REALLY can't determine a maximum or minimum amount of objects, or there is a huge need for the memory at a specific time.

Just work out how many bullets could possibly be on the screen at any one time, and size the array accordingly.

EDIT 2: there are methods in the std::vector definition that allow you to remove specific elements from the list, I believe vec.erase(location); will remove the element, and deallocate the memory I hope :lol:

Re: Destroying objects help

Posted: Fri Jun 05, 2009 5:49 pm
by Falco Girgis

Code: Select all

if(bulletVector[index].x > SCREEN_WIDTH || bulletVector[index].x < 0 || bulletVector[index].y < 0 || bulletVector[index].y > SCREEN_HEIGHT) bulletVector.erase(bulletVector.begin() + index);
index is the current bullet.

Re: Destroying objects help

Posted: Sat Jun 06, 2009 2:54 am
by Panama
Thank you both for your replies. I did consider using arrays but to be honest I have always been more of a vectors kind of man plus they have nice functionality for handling objects that need to be built and destroyed quickly like these. I found the erase function to work perfectly however, I can now have lag free games! :lol:

Anyway, thanks dudes for your input