Search code examples
javascriptgame-developmentphaser-frameworkphaserjs

Adding Sprite to a Layer causes it to be at top instead of with the layer


I am adding a sprite to a group, and I expected it to be with the group’s layer, instead it is brought to the top of the canvas. Any ideas?

Code:

this.backObjects.add(this.target); //supposed to be in back
this.targetClone = this.add.sprite(this.target.x, this.target.y, this.target.texture.key);
this.targetClone.setScale(3);
this.frontObjects.add(this.targetClone); //supposed to be in front
//both are in the front

[…]
//puts backObjects in back when player is below it
this.backObjects.getChildren().forEach(function(object){
    if(object.y>this.player.y){
        object.visible = false;
    } else if (object.y <= this.player.y){
        object.visible = true;
    }
}, this);
//puts frontObjects in front when player is above it
this.frontObjects.getChildren().forEach(function(object){
    if(object.y>this.player.y){
        object.visible = true;
    } else if (object.y <= this.player.y){
        object.visible = false;
    }
}, this);

both are in front


Solution

  • Depending on the exact usecase it might be enough to set the depth instead of the visibility of the object to a higher number, using the setDepth function (link to the documentation). If you are using tilemaps checkout this question/answer it have a working demo for two layers and a player

    If you want more accuracy, "the player can be behind the top half of the sprite", you would have to compare in the update function the y position of the objects and set there depth accordingly, but this would be alot of work using 2 layer with tilemap is a beter option.

    btw.: just to be on the save side, when comparing the y position of the object don't forget to consider the origin and size(width/height) of the object, if not images can overlap without triggering the switch.