问题
I want to make a top-down 2d shooting game using libgdx. There will be a lot of bullet objects that I want to keep track of and dispose when they go off the screen. I was thinking that I would use something like
static ArrayList<Bullet> bullets;
to keep track of my bullets in the Bullet class, check this array list for any bullets that are off the screen, dispose of them if they are, and delete that bullet from the ArrayList. I was wondering if this is the best way to do this. It seems like something that should be pretty common and so I wanted to make sure that this is the best way of doing this.
回答1:
Using an object pool is a better approach.
The idea of an object pool is simple and fits perfectly for your needs in this case. The pool handles creating and storing the Bullet
objects. All you have to do is to call the obtain
method of the pool when you need a bullet (User shoots) and call the recycle method of the pool for this bullet when it's no longer needed in the game (Goes offscreen).
Here is a code example for a pool taken from AndEngine's source. You can use it to learn how it works and make your own pool class (Or use this one).
来源:https://stackoverflow.com/questions/13253535/keeping-track-of-unnamed-objects