Created
November 18, 2015 01:20
-
-
Save aerze/0792e325c83abb626c19 to your computer and use it in GitHub Desktop.
Creating object pools in Phaserjs
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
// create a group that will hold all the targets | |
var setupTarget = function() { | |
targetPool = game.add.group(); | |
// enable physics | |
targetPool.enableBody = true; | |
targetPool.physicsBodyType = Phaser.Physics.ARCADE; | |
// pre-create a pool | |
targetPool.createMultiple(15, 'target'); | |
// set default properties | |
targetPool.setAll('scale.x', 1.5); | |
targetPool.setAll('scale.y', 1.5); | |
targetPool.setAll('anchor.x', 0.5); | |
targetPool.setAll('anchor.y', 0.5); | |
targetPool.setAll('outOfBoundsKill', true); | |
targetPool.setAll('checkWorldBounds', true); | |
} | |
// Actualyl spawn a new one | |
var spawnTarget = function () { | |
// they're all alive, can't spawn a new one (without removing an existing one) | |
if (this.targetPool.countDead() <= 0) return; | |
// get reference to a target from the pool | |
var target = targetPool.getFirstExists(false); | |
// enable physics (not sure if you have to do this one); | |
game.physics.enable(target, Phaser.Physics.ARCADE); | |
// this is like game.add, place target in a new location | |
target.reset(-50, game.rnd.integerInRange(200, game.height - 200), 1); | |
// set some defaults | |
target.body.allowGravity = true; | |
target.body.moves = true; | |
target.body.gravity.setTo(0, 500); | |
target.body.drag.x = 10; | |
target.body.bounce = 0.5; | |
target.body.velocity.setTo(700, -350); | |
// enable input, run callback addToScore on input UP | |
target.inputEnabled = true; | |
target.events.onInputDown.add(addToScore, this); | |
}, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment