2
votes

Is it possible to display a child sprite behind a parent sprite with Phaser? I'd like to draw a ring around my sprite by rendering a filled green circle and sticking it behind the parent sprite. I know I can use a group for this, but I want the parent sprite to be affected by physics and don't know how to reconcile this with the group usage.

Here is a jsfiddle of my issue: http://jsfiddle.net/omm0vvfv/

<script src='https://rawgit.com/photonstorm/phaser/master/build/phaser.js'></script>
<script>
var game = this.game = new Phaser.Game(800, 400, Phaser.AUTO, '', {
  create: function() {
    game.physics.startSystem(Phaser.Physics.ARCADE);

    var main_sprite = game.add.sprite(200, 200, 'foo-sprite')
    main_sprite.anchor.setTo(.5, .5)
    game.physics.arcade.enable(main_sprite)
    main_sprite.body.gravity.y = 30

    var bmd = this.game.make.bitmapData(main_sprite.width * 2, main_sprite.width * 2)
    bmd.circle(bmd.width * .5, bmd.width * .5, main_sprite.width, '#0000ff')
    var ring_sprite = this.game.make.sprite(0, 0, bmd)
    ring_sprite.anchor.setTo(.5, .5)

    // I can get the ring behind the sprite like this, but it doesn't stick.
    var group = game.add.group()
    group.add(ring_sprite)
    group.add(main_sprite)
    ring_sprite.x = main_sprite.x
    ring_sprite.y = main_sprite.y

    // If I do this it sticks, but I can't get it behind the sprite.
    // main_sprite.addChild(ring_sprite)
  }
})

</script>

Edit: I realized I could set the ring position to the main sprite's position in my update function: http://jsfiddle.net/jqto6z72/

But then I have another problem. As you can see the ring seems to lag behind the sprite a bit. So it is rendered slightly higher than it should be. I think this is because the physics updates after I set the ring's position. Is there a way to set the ring's position after the physics update but before the render?

1

1 Answers

2
votes

If you need to sync a manual object to a physics based one then I would recommend you do it in the preRender method of your State. This is called immediately after the State update has finished processing, but before it renders.