Phaser 3 - destroy after animation?

Hi,

So I am trying to destroy an animation after it is finished… I looked it up and there are .on(‘animationcomplete’…) and .onComplete.add()… I am not sure which method I should use or there is another way that is more efficient? Also, should I use disableBody, or destory, or remove to completely remove an object with animation?

Here is how I defined the object:
var delayBox = 5000;

    box = this.physics.add.staticGroup();

    this.time.addEvent({
        delay: delayBox,
        callback: spawn,
        args: ['box'],
        loop: true
    });

    this.anims.create({
        key: 'idleBox',
        frames: [{key: 'box', frame: 0}],
        frameRate: 20,
        repeat: -1
    });

    this.anims.create({
        key: 'breakBox',
        frames: this.anims.generateFrameNumbers('box', {start: 0, end: 4}),
        frameRate: 10
    })

So after the breakBox animation, I want it to be removed…
function hitBox(player, box) // called my collider
{
box.play(‘breakBox’,false);
box.onComplete??? <— i need to remove here
}

This should do it

hitBox(player, box) {
  box.play('breakBox', false)
  box.once(Phaser.Animations.Events.SPRITE_ANIMATION_COMPLETE, () => {
    console.log('SPRITE_ANIMATION_COMPLETE')
  })
}

hmmm correct me if I am wrong, I tried this:
function hitBox(player, box)
{
box.play(‘breakBox’, false);
box.once(‘completeanimation’, destroyBox)
}

function destroyBox(player, box)
{
    box.destroy();
}

but it did not work…, I assumed the once method will send over “player” and “box”.

Try this

function hitBox(player, box) {
  box.play('breakBox', false)
  box.once('animationcomplete', (box)=>{
    box.destroy()
  })
}

Tried this, too. The animation part works, but after the animation the box is still there.

My bad. The listener function should be a anonymous function.

function hitBox(player, box) {
  box.play('breakBox', false)
  box.once('animationcomplete', () => {
    console.log('animationcomplete')
    box.destroy()
  })
}
2 Likes

Thank you, i have tried and successe