Using object pools in Libgdx

I am creating a game for Android that uses the Entity object class, which then expands into many different types (e.g. opponents, bullets, etc.). Is there a way to create a pool of type Entity and then convert the resulting Entity objects to what I need at runtime (say, bullet type)? Passing an object as an argument to the constructor will simply eliminate the pool's purpose? The following is an example:

public class EntityPool extends Pool<Entity> { public EntityPool (int initialCapacity, int max) { super(initialCapacity, max); } protected PooledEntity newObject () { return new PooledEntity(); } public Entity obtain (int objectType) { Entity ent = super.obtain(); if (objectType==SOME_OBJECT_TYPE) //Do something to make ent into that object type return ent; } public class PooledEntity extends Entity { PooledEntity () { super(null, 0, 0); } public void free () { EntityPool.this.free(this); } } 

}

+2
java android libgdx
source share
2 answers

With your current code, your pool can store any object that is an entity or subclass of the object. As a result, you can use instanceof or downcast to get the type of a specific object.

If you want to have different pools for each type, you can consider changing the pool declaration:

 public class EntityPool<T> extends Pool<T extends Entity> 

And then, for example, there is:

 EntityPool<Bullet> bulletsPool = new EntityPool<Bullet>(); //only objects of Bullet of sub classes can be added 
0
source share

The point of the pool of objects is usually to avoid the overhead of distributing and freeing the system, and requires that you know the β€œworst” limit on the amount of each type of object that you want to allocate. Therefore, assuming that your entities are different in life and use, you probably want to have separate pools for each object. (You can definitely improve the pool, as in @zaske's answer.)

On the other hand, if you really need a single Entity pool, and you want to configure these objects at runtime, you can move from using Entity subclasses to something like:

 class Entity { EntityCustomizer custom; ... } 

Then, choosing Entity from the pool, you pass Bullet or Ship or any other customizer:

 public Entity obtain (int objectType) { Entity ent = super.obtain(); if (objectType==SOME_OBJECT_TYPE) ent.custom = EntityCustomizer.SOME_OBJECT_TYPE_IMPL; return ent; } 

(I am sure this is a well-known pattern, and I should use the appropriate language to identify the parts ...)

All of this, I think that separate pools for each Entity type are the way to go, since my work is pretty negligent (you trade a bunch of compilation type checks for some flexibility at runtime).

+1
source share

All Articles