Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LibGdx Object Pool for many objects of the same parent class

In my game bullets are constantly created, therefore I want to use Pool class for this. However, the problem is that I have many types of bullets. All of them extend the same parent class Projectile. Currently there are 19 types of bullets. It's a bad idea to create a Pool class for each of them. And more may come later.

I tried to cast BallistaArrow arrow = (BallistaArrow) world.getPool().obtain(); . However I'm getting cast exception:

[..].mygame.Projectile cannot be cast to [...].mygame.engineer.BallistaArrow .

BallistaArrow is the child class of Projectile.

Is there any way to solve this problem, so that I can have one Pool class for all Projectile extending objects?

like image 624
draziw Avatar asked Nov 09 '13 21:11

draziw


1 Answers

The pool contains instances of a specific type. Say it has 10 objects in it, those are going to be 10 specific Projectile instances, you cannot decide which type the object is after you extract it from the pool.

There are two ways to solve this, at least:

  1. Use multiple pools, one per bullet type. You can put a wrapper around the pools that knows which one to use based on a typed parameter. This is probably not that bad of a solution. An empty pool isn't a big deal. You may have retention problems if some class of projectile is used for a while, and then isn't used (its pool will still be full).
  2. Make your Projectile sub-types a run-time specialization, not a subclass. So you just have a Projectile class that stores stuff common to all your bullets, and figure out the behavior difference at run-time. See Using Object Pools in Libgdx.
like image 161
P.T. Avatar answered Nov 08 '22 12:11

P.T.