Created
June 21, 2012 19:41
-
-
Save martinwells/2968030 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// declare bullet pools | |
var activeBullets = []; | |
var bulletPool = []; | |
// construct some bullets ready for use | |
for (var i=0; i < 20; i++) | |
bulletPool.push( new Bullet() ); | |
// a constructor/factory function | |
function getNewBullet() | |
{ | |
var b = null; | |
// check to see if there is a spare one | |
if (bulletPool.length > 0) | |
b = bulletPool.pop(); | |
else | |
// none left, construct a new one | |
b = new Bullet(); | |
// move the new bullet to the active array | |
activeBullets.push(b); | |
return b; | |
} | |
function freeBullet(b) | |
{ | |
// find the active bullet and remove it | |
// NOTE: Not using indexOf since it wont work in IE8 and below | |
for (var i=0, l=activeBullets.length; i < l; i++) | |
if (activeBullets[i] == b) | |
array.slice(i, 1); | |
// return the bullet back into the pool | |
bulletPool.push(b); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, thanks for sharing this! I'm using a very similar code inspired on this gist for a game engine I'm building but looking to improve performance. Could you please explain line 32 "array.slice(i, 1);"? I'm using splice activeBullets on this line but splice is expensive and would rather use slice. However, I don't understand how slicing would work here and where "array" comes from.. or is this a native js function. FYI: I'm looping through activeBullets to update/draw my objects. Any help would be appreciated. Cheers!