Creating/adding sprites in create() vs. update()


I am a noob when it comes the Phaser. I searched around (both forums and Google) and couldn’t find an example of what I’m trying to do…

I have a game where the number of sprites (or their associated images) is not known when the create() function is called. The images available are known, just not which sprites will use which images.

There is a server which is providing the number and location of sprites, and I am trying to use the following during update() to display them:

        if (bot.sprite == undefined)
            // Must be a new enemy bot, generate the sprite now
            let sprite = new Phaser.GameObjects.Sprite(mainScene, 0, 0, 'chassis2');
            bot.sprite = sprite;
        if (bot != playerbot)
            // Calculate the relative position of the bot from the player
            let posx = bot.posx - playerbot.posx;
            let posy = bot.posy - playerbot.posy;
            // Convert the relative position into screen coordinate
            posx = 400 + posx;
            posy = 300 - posy;
            bot.sprite.setPosition(posx, posy);

When I do this the sprites appear and move as expected, but the graphics behind the sprite are not restored as the sprite moves. Instead there is a black trail that comes from the outline of the moving sprite.

I am pretty confident that this is related to creating the sprite in the update method. To troubleshoot, I created a global “sprite2” and instead of creating a new sprite and adding it I simply made it visible. There are no issues when I do that.

Not that it should matter - the non-moving sprite is depth 0, and the dynamically created moving sprite is depth 1.

Another thing I noticed is that although setPosition() does move the sprite, when I dump the sprite’s JSON I noticed that x and y are not set - the JSON has it at 0,0 all the time.


I am using Phaser 3.17.


I can’t tell from the code what exactly is going wrong, but I can all but guarantee that the “black trail” are actually sprites, lots and lots of sprites - so I guess at some point bot.sprite is set to undefined again, or the bot object is recreated or something along those lines.

To debug this I would advise to simply put a

 console.log("new sprite")

before or after the sprite creation.

I am confident, that the console will be spammed with messages.
(Because getting a trail is only possible by adding more and more sprites or explicitly using graphics objects to render to, because everything else is redrawn from scratch for every frame.)


the “black trail” are actually sprites, lots and lots of sprites - yup!

Should have mentioned that I am also new to Javascript! Thanks for the help!