Input down events for all children in a group in phaser ce
These days I have been playing around with groups in phaser ce, and have learned a lot about what there is to work with in the Phaser.Group class allowing me to make smarter decisions when developing a project with phaser ce. For example when it comes to attaching an event hander for sprites, I can attach one for each sprite in a group. However if it is something that applies to all of the children in a group, I can use Group.onChildInputDown.
1 - What to know before continuing
2 - An example using group.onChildInputDown
For an example of group.onChildInputDown I made a quick project that involves making a small group of block sprites using a canvas solution to make the sprite sheet. Each time a sprite is clicked a handler that is attached to the group thanks to group.onChildInputDown is called that reduces the health property of the sprite that was clicked. When the health of a sprite reaches zero it dies, and if all sprites in the group die the group is reset.
2.1 - The handler to be used with group.onChildInputDown
This is the handler that will be called each time a sprite is clicked. I could attach the handler on a per sprite bases, but because it applies to all sprites in the group, I can attach it here.
2.2 - Create the group, and attach the handler with group.onChildInputDown
Now that I have a handler I can attach the handler to a group with group.onChildInputDown, but first I need a group to attach to. So I made a group, and created a bunch of sprites with group.create. In then call my reset group method that I will get into in a bit, and why that is important. Then of course I attach the onBlockInputDown handler to the group.
2.3 - Reset group helper
Here I have a method that will reset the group, or set it for the first time. Here I make sure that the inputEnabled boolean is set true if it has not yet, and use the revive method to set the health property of the sprite to 5. I then also use Group.align to align the position of the sprites into a grid formation as well, and set the position of the group in a similar matter to that of any other display object in phaser.
2.4 - Make a sprite sheet with canvas
2.5 - The Phaser.Game instance
Now it is time to pull everything together with a Phaser.Game instance. With this example I just need to do everything in a single create method in a single state object sense everything is event driven, and I have off set just about all of the logic into small helper methods in an effort to make the code more fine grain.
3 - Conclusion
There is of course also attaching events on a per sprite basis as well, so I a read project there might be a situation in which I attach one or more handlers via group.onChildInputDown as well as a few handers here and there via Sprite.events.onInputDown as well.