Previous Phaser tutorials:
Phaser tutorial: Phaser and Spriter skeletal animation
Phaser tutorial: DronShooter - simple game in Typescript - Part 3
Phaser tutorial: DronShooter - simple game in Typescript - Part 2
Phaser tutorial: adding 9-patch image support to Phaser
Phaser tutorial: DronShooter - simple game in Typescript - Part 1
Phaser tutorial: custom easing functions for tweening and easing functions with parameters
Phaser tutorial: sprites and custom properties for atlas frames
Phaser tutorial: manage different screen sizes
Phaser tutorial: How to wrap bitmap text
When building scene tree in Phaser engine the sprites added as last are rendered on top. Unlike, for example, in Unity, you cannot change order of sprites with setting its z position. You can only set z property and sort sprites within one group.
Now, take a look at following example:
You can try to achieve this with:
- making two groups (walls and gems) and tween them. But, in such case all gems will be under or above walls, depending on groups order,
- making one group with all the walls and gems, but to move them you will have to create 8 tweens.
There is third way which allows you to put all sprites in one group (like in 2.) and transform gems and walls at once (like in 1.).
To achieve it you have to create 3 groups: one for all the sprites and two empty. In group with sprites you will maintain your z order and empty groups will be tweened. Now comes the trick - sprites will not be transformed with their parent group, but walls will be transformed with on of the empty groups and gems with the second. In other words: when engine is transforming sprite, you give it group parent different from its original one.
Source code for this example is short and self explanatory. Sprites are created and added to spritesGroup. All sprites are MySprite class objects and they are given another group they will use as their parent when updating transform. Two empty groups are named group1 and group2. These groups are then tweened.
While the code is simple, the final effect looks like complicated pattern of sprites and groups.