currently working on a very simple game using Pixi.js for fun and I'm running into an issue.
I need to remove a specific instance of a function from the ticker once a specific sprite has been removed from the stage.
When space is pressed I call createBullet()
function createBullet(sheet, sprite) {
const bullet = new PIXI.Sprite(sheet.textures["sample.png"]);
bullet.x = sprite.x
bullet.y = sprite.y + 10
bullet.height = bullet.height / 5
bullet.width = bullet.width / 5
app.stage.addChild(bullet);
bullet.ticker.add((delta) => { moveBullet(delta, bullet) })
}
createBullet creates a new sprite, adds it to the stage and then adds moveBullet() to the ticker
function moveBullet(delta, b) {
// move bullet
b.y += (-BULLETSPEED * delta)
// delete bullet once out of bounds
if (b.y < -10)
{
app.stage.removeChild(b);
}
}
I am looking to remove moveBullet() from the ticker onces the bullet its moving has been removed from the stage.
I tried placing a while loop in moveBullet() that checks if b is not null and setting b to null after it has been removed from the stage. and then adding moveBullet to the ticker using addOnce() instead of add(). this did not work.
I know I can use ticker.remove() to remove a tick but im not sure how to remove a specific instance of the moveBullet function.
how would I go about doing this?
I figured it out a couple of minutes after posting so I'll post my solution incase it helps anyone in the future.
My inital mistake was using the app ticker. Instead my createBullet() function now creates a new ticker for each bullet. That ticker is destoryed by moveBullet() when the bullet moves out of bounds.
function createBullet(sheet, sprite) {
const bullet = new PIXI.Sprite(sheet.textures["sample.png"]);
bullet.x = sprite.x
bullet.y = sprite.y + 10
bullet.height = bullet.height / 5
bullet.width = bullet.width / 5
app.stage.addChild(bullet);
const bullet_ticker = new PIXI.Ticker
bullet_ticker.add((delta) => { moveBullet(delta, bullet, bullet_ticker) })
bullet_ticker.start()
}
function moveBullet(delta, b, ticker) {
// move bullet
b.y += (-BULLETSPEED * delta)
// delete bullet once out of bounds and remove its ticker
if (b.y < -10)
{
app.stage.removeChild(b);
ticker.destroy()
}
}