How can I use an object pool for optimization in AndEngine?

Posted by coder_For_Life22 on Game Development See other posts from Game Development or by coder_For_Life22
Published on 2011-12-21T19:59:52Z Indexed on 2012/03/19 18:15 UTC
Read the original article Hit count: 187

Filed under:

I have read up on a tutorial that allows you to reuse sprites that are re-added to the scene such as bullets from a gun or any other objects using an ObjectPool.

In my game i have a variation of sprites about 6 all together with different textures.

This is how the object pool is set up with its own class extending Java's GenericPool class

public class BulletPool extends GenericPool<BulletSprite> {
private TextureRegion mTextureRegion;

 public BulletPool(TextureRegion pTextureRegion) {
  if (pTextureRegion == null) {
 // Need to be able to create a Sprite so the Pool needs to have a TextureRegion
 throw new IllegalArgumentException("The texture region must not be NULL");
 }
 mTextureRegion = pTextureRegion;
} 

/**
* Called when a Bullet is required but there isn't one in the pool
*/
@Override
protected BulletSprite onAllocatePoolItem() {
return new BulletSprite(mTextureRegion);
 }

/**
 * Called when a Bullet is sent to the pool
*/
@Override
protected void onHandleRecycleItem(final BulletSprite pBullet) {
pBullet.setIgnoreUpdate(true);
pBullet.setVisible(false);
}

  /**
  * Called just before a Bullet is returned to the caller, this is where you write  your initialize code
* i.e. set location, rotation, etc.
 */
   @Override
 protected void onHandleObtainItem(final BulletSprite pBullet) {
  pBullet.reset();
}
}

As you see here it takes a TextureRegion parameter. The only problem i am facing with this is that i need to have 6 different sprites recycled and reused in the ObjectPool. This ObjectPool is set up to only use one TextureRegion.

Any idea's or suggestions on how to do this?

© Game Development or respective owner

Related posts about android