The theory http://gameprogrammingpatterns.com/object-pool.html by Bob Nystrom aka @Munificentbob

Example implementation of Object Pooling pattern in AS3

package
{
	import flash.utils.Dictionary;
	
	public class Pool
	{
		private static var _instance:Pool;
		private var _pool:Dictionary = new Dictionary;
		
		public function Pool(lock:SingletonLock)
		{
		}
		
		public static function get instance():Pool
		{
			if (_instance == null)
			{
				_instance = new Pool(new SingletonLock());
			}			
			
			return (_instance);
		}
		
		// create a new pool
		public function pool(poolName:String):Array
		{
			if (_pool[poolName] == null)
			{
				_pool[poolName] = [];
			}
			return _pool[poolName];
		}
		
		// delete the ref
		public function del(poolName:String):void
		{
			delete _pool[poolName];
		}
	
	}
}

class SingletonLock
{
}

As you can see, my implementation is based on a Singleton pattern.

Here how to use it
Step 1) Filling the pool with some objects during the preload/init of the level

var bulletPool:Array = Pool.instance.pool("bullets"); // create the pool if necessary

// Create 15 bullets ready to use
for (var i:int = 0; i #60; 15; i++)
{
bulletPool.push( new Bullet() ); 
} 

Step 2) during the game when you need to shoot a bullet

var bullet = bulletPool.length ? bulletPool.pop() as Bullet : new Bullet(); // take a bullet if any or create a new one
bullet.init( { visible:false,x:originX,y:originY } ); // initialize the bullet
addEntity(bullet); // put it on screen

Step 3) When the bullet is destroyed, for example during a collision

Pool.instance.pool("bullets").push( bulletReference ); // push back the bullet into the pool

Demo :

You can change speed of the bullet :
Pool size is the number of sleeping objects that are ready to use
Bullet in use is the number of bullet on screen

Pool.as – Download Download

Note : Aquamentus is the first boss of the Legend Of Zelda (NES) ^^


Vote in HexoSearch