Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply an action to every object in group for Phaser js

As it says, in Phaser.js how can you apply an action for each object inside a group. I want to apply the following lines to each item:

game.physics.arcade.collide(something, platforms);
game.physics.arcade.overlap(player, something, gameOver, null, this);
something.body.velocity.x = -120;

"Something" is the object name but my group name is called "obstacleGroup". I want to do this as I have another function making new objects to the group all the time so I don't necessarily know what they are being called.

like image 818
Andrew Junior Howard Avatar asked Nov 29 '22 11:11

Andrew Junior Howard


2 Answers

Group.forEach is one such iteration method you could use (as @imcg pointed out before me). However you're using it for Arcade Physics collision, and that can take a Group as the parameters. So you could collide everything in your Group vs. platforms with just:

game.physics.arcade.collide(obstacleGroup, platforms);

Once, in your update loop.

Same works for overlap.

like image 118
PhotonStorm Avatar answered Dec 09 '22 20:12

PhotonStorm


You can use Group.forEach to iterate the objects in the group and call a function on them:

obstacleGroup.forEach(function(item) {
    game.physics.arcade.collide(item, platforms);
    game.physics.arcade.overlap(player, item, gameOver);
    item.body.velocity.x = -120;
}, this);
like image 20
imcg Avatar answered Dec 09 '22 21:12

imcg