HTML and CSS Reference
In-Depth Information
// Resize our elements array
this.elements.length = newsize;
for( var i = oldsize; i < newsize; i++ ){
// Add a new element to our pool
this.elements[i] = new demo.Particle( i );
// Add its index to the free elements array
this.freeElements.push( i );
console.log( 'Pool grown from ' + oldsize + ' to ' + newsize + ' particles.' );
Requesting a Free Object from the Pool
When you need a free object, instead of creating a new object, you ask the pool for one.If no free objects are left, the
pool has to be grown.
The object is also reset. As for your particles, you reset their position, velocity, and acceleration; otherwise, the
particles will spawn with increasing speed as the simulation runs. If you forget to reset the object properties, you may
have unexpected bugs in your game. These bugs can be hard to figure out, so double-check, triple-check, and unit test
that your objects are reset properly.
Here's the particle reset code, straight from the demo:
RecyclableParticle.prototype.reset = function() {
this.setup( 0, 0, 0, 0, 0 ); // reset size and position
this.setVel( 0, 0 ); // reset velocity
this.acc.x = 0; // reset acceleration x
this.acc.y = 0; // reset acceleration y
return this; // so our particle API is chainable
The pool will quickly find a free object by looking to the free-indexes array. If an array is empty, it will grow
itself again. The pool will both remove the index of its internal-indexes array and mark the object as allocated before
returning it, as shown in Listing 3-3.
Listing 3-3. Following a Request for a Free Object, Object 8 Has Been Returned and Marked as Allocated, and Its
index, Removed from the Free-Indexes Array
demo.ParticlePool.prototype.getFree = function(){
if( this.freeElements.length === 0 ){
// no free particles left, grow the pool
Search WWH ::

Custom Search