Jump to content

Make a sprite follow smoothly another one


Recommended Posts


Consider the following code:

mySprite.addChild(game.add.sprite(0, 5, 'shadow'));

This has the effect of adding a shadow to a sprite. The cool thing is that the shadow will follow the parent sprite extremely smoothly, without any apparent lag. My question is, how could I emulate such a smooth "tracking" behavior without using addChild() ? I tried something as follow:

// In create() :

var player = game.add.sprite(100, 100, 'player'));
var shadow= game.add.sprite(100, 105, 'shadow'));

// In update() :

shadow.x = player.x
shadow.y = player.y + 5

That is, manually associating the coordinates of both sprites in the update loop. It works, but it's much less smooth, and you can see the shadow always lagging a bit behind. Visually speaking, it's not satisfactory at all.

What sorcery takes place under the hood that makes it work fine with addChild(), but not when doing it manually in the update loop (I didn't find anything conclusive in the code, but I guessed I didn't look right)? Is it possible to reproduce? Thanks for your tips.

NB: I need this because I'm in a situation where the parent sprite (e.g. the player) should be rendered below some sprites, while child sprite (e.g. the shadow) should be rendered on top of them. If I put the parent and child sprites in different groups, the rendering is ok, but the following behavior becomes laggy. If I add the child to the parent using addChild, the following behavior is ok but then I can't figure how to render parent and child on two completely different levels.

Link to comment
Share on other sites


  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...