Skip to content

Instantly share code, notes, and snippets.

@pctroll
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pctroll/807fc644b3e4f05e2244 to your computer and use it in GitHub Desktop.
Save pctroll/807fc644b3e4f05e2244 to your computer and use it in GitHub Desktop.
How to use Phaser.Group.forEach
create: function () {
var offsetX = 120; // offset from the screen border
var offsetY = 30;
var margin = 10; // margin between enemies
var rows = 4;
var cols = 6;
// loop for using the offset and margin variables
this.enemies = game.add.group();
for (i = 0; i < rows; i++) {
for (j = 0; j < cols = j++) {
var ship = this.enemies.create(0, 0, img);
ship.x = ship.width * j + margin + offsetX;
ship.y = ship.height * i + margin + offsetY;
}
}
},
update: function () {
// how to call the forEach function
this.enemies.forEach(this.moveEnemy, this);
},
// the function to be called for each element in the group
moveEnemy: function (enemy) {
var speed = 10;
enemy.x += game.time.physicsElapsed * speed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment