Owen Greenhalgh
Owen Greenhalgh

Reputation: 65

Issue with deleting sprites from a group in Phaser 3

I have a level creating platformer game that I have been making. In my update loop, if my selected block type is -1, and the mouse is down, then it iterates through a group containing sprites for my game.

In this iteration, I have some code that checks if our mouse is touching that sprite. If it is touching it, then the sprite is destroyed with the destroy(); function. If I only have one sprite in the game, then it works fine, but otherwise it gives me the error "Uncaught TypeError: Cannot read properties of undefined (reading 'body')". I would like it to delete when my mouse touches it. Any help with this would be greatly appreciated.

Upvotes: 2

Views: 355

Answers (1)

winner_joiner
winner_joiner

Reputation: 14760

Well the problem is, that the update function is call so fast, that the destroy function is called multiple times on the same child, before it is fully destroyed. You could just add an extra check in your if-clause, before you call the destroy function.

Something like this, should do the trick:

coins.children.iterate(function(child) { 
    if ( child && child.body && [mouse touching coin] ) { 
        child.destroy(); 
    } 
});

Upvotes: 1

Related Questions