how to delete a sprite in an sprite array in pixi.js

Viewed 105

I want to delete a sprite from my sprite array and I tried myPlane.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
}

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?
1 Answers

Unfortunately myPlane.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
}

Generally speaking, you should avoid mutating the array that you are looping through. If you don't keep references to the bullets 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
}
Related