Question:
I want to delete a sprite from my sprite array and I triedmyPlane.bullets[index].destroy()
and myPlane.bullets.shift()
:for (let index = 0; index < myPlane.bullets.length; index++) { if(myPlane.bullets[index].y < -bulletHeight) { // step 1 myPlane.bullets[index].destroy() // step 2 myPlane.bullets.shift() continue } myPlane.bullets[index].y -= bulletSpeed [/code]
}but I think that’s not the best way to delete a sprite in an array, it is too fussy.
Is there a better way to delete a sprite in an array?
Answer:
UnfortunatelymyPlane.bullets.shift()
will only remove the first element of the array. To remove an element by index you need to use myPlane.bullets.splice(i, 1)
.Keep in mind that this affects the original indexes of the objects. If you don’t handle it, the for loop will continue increasing and will skip one element.
for (let index = 0; index < myPlane.bullets.length; index++) { if (myPlane.bullets[index].y < -bulletHeight) { // step 1 myPlane.bullets[index].destroy() // step 2 myPlane.bullets.splice(index, 1) index-- // compensate array length mutation continue } myPlane.bullets[index].y -= bulletSpeed } [/code]
Generally speaking, you should avoid mutating the array that you are looping through. If you don’t keep references to thebullets
array, here is an alternative where a new filtered array is created:myPlane.bullets = myPlane.bullets.filter((bullet) => {
if (bullet.y < -bulletHeight) {
bullet.destroy()
return false
}
return true
});
for (let index = 0; index < myPlane.bullets.length; index++) {
myPlane.bullets[index].y -= bulletSpeed
}
[/code]
If you have better answer, please add a comment about this, thank you!