0

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.

russjohnson09
  • 271
  • 3
  • 15
  • `static` is debatable, depending on your project setup, but in general, yes, a list of bullets is a typical way to do this. – Geobits Nov 06 '12 at 14:55

1 Answers1

3

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).

Jong
  • 9,045
  • 3
  • 34
  • 66
  • Here is pool for libgdx. http://libgdx.l33tlabs.org/docs/api/com/badlogic/gdx/utils/Pool.html – russjohnson09 Nov 06 '12 at 15:06
  • Both are not associated with their framework, so you can use them anywhere in any java (Only a few debugging lines in AndEngine's pool depend on the framework.. Delete them) – Jong Nov 06 '12 at 15:09
  • I agree with using a pool to minimize object creation, etc. He still needs a list of *active* bullets to iterate through, though, no? Unless you incorporate that into the pool itself, which neither linked pool class shows. – Geobits Nov 06 '12 at 15:11
  • I've put the code to do this job in my pool code (Of one of my games). It's something game dependant, and you can definitely add it in the pool's code. – Jong Nov 06 '12 at 15:16