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');
mainScene.add.existing(sprite);
sprite.setDepth(1);
sprite.setScale(0.3);
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.