• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: how to delete a sprite in an sprite array in pixi.js

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

0
By Isaac Tonny on 18/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

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 [/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:

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 } [/code]

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 } [/code]

If you have better answer, please add a comment about this, thank you!

pixi.js
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: How do I use SetWindowText with Unicode in Win32 using PowerShell?

01/04/2023

Resolved: Shopware 400 Status Error “This value is too long. It should have 255 character or less.” When I Try Updating Database Table

01/04/2023

Resolved: Using AWK to count multiple patterns in a file

01/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.