Bring graphics on top of Dynamically added sprite in Phaser

Bimal Bose B S picture Bimal Bose B S · May 11, 2014 · Viewed 8k times · Source

I am adding Sprites dynamically by using a timed event. I can't find a way to bring a new graphics (a flooded rectangle) above the sprites generated.

The sprites are always on top

create()
{
  var graphics = game.add.graphics(0, 0);
  graphics.beginFill(0xFFFF0B);
  graphics.drawRect(0, 0, windowWidth, 70);
  graphics.endFill();
  timer = game.time.events.loop(1500, addSprite, this);
}

addSprite()
{  
  sprite= game.add.sprite(20, 30, 'sprite');
}

Any help??

Answer

PhotonStorm picture PhotonStorm · Jun 2, 2014

Graphics objects in Phaser are just standard display list objects like Sprites are. They are added to the World by default (as Sprites are), and you can move them around using Phaser.Group level commands like moveUp, moveDown, bringToTop, etc. You'll find a complete list here: http://docs.phaser.io/Phaser.Group.html

So once you've added your Sprite in the code above, bring your Graphics object to the top of the Group:

game.world.bringToTop(graphics);

Note: At the moment you have a local var graphics, so you'll need to make that visible to the rest of your functions for this to work.