Bullet lifespan (Phaser 3)

Since Phaser v3.50.0 the WORLD_STEP event passes the Arcade Physics delta time. You can use it to implement precise bullet lifespans. Bullet lifespans are slightly simpler than bullet ranges since no distances need to be calculated.

function fireBullet (bullet)
{
  // …
  bullet.setState(BULLET_LIFESPAN);
}

function updateBullet(bullet, delta) {
  bullet.state -= delta;

  if (bullet.state <= 0) {
    bullet.disableBody(true, true);
  }
}

1 Like

I’m trying that piece of code:

let bullet_lifespan  = 2;
//create function
this.physics.world.on('worldstep', updateBullet);

//fire bullet function
bullet.setState(bullet_lifespan);

//other function
function updateBullet(bullet, delta) {
	bullet.state -= delta;

	if (bullet.state <= 0) {
		console.log('bullet destroyed');
		bullet.disableBody(true, true);
	}
}

but I get this error:
Cannot create property ‘state’ on number '0.016666666666666666

The arguments don’t match here. The worldstep event passes only (delta). You can do

this.physics.world.on('worldstep', (delta) => {
  updateBullet(bullet, delta);
});

If you have multiple bullets (the usual case), you should loop through them.

2 Likes