Rate of fire : explanation please

Hello,

I have some trouble to understand a piece of code related to the rate of fire of a machinegun, can someone explain it to me with simple words please ?

Here’s the code I don’t understand :

// If there is more than one bullet between the last and this frame
// Reset the nextFireTime
if (Time.time - fireRate > nextFireTime)
	nextFireTime = Time.time - Time.deltaTime;

The context:

function Fire ()
{
	if (bulletsLeft == 0)
	return;
	
	// If there is more than one bullet between the last and this frame
	// Reset the nextFireTime
	if (Time.time - fireRate > nextFireTime)
		nextFireTime = Time.time - Time.deltaTime;
	
	// Keep firing until we used up the fire time
	while( nextFireTime < Time.time && bulletsLeft != 0)
	{
	FireOneShot();
	nextFireTime += fireRate;
	}
}

FPS Tutorial (
MachineGun.js)

This code increments nextFireTime by fireRate after each shot. When you stop firing, nextFireTime stops too. When shooting again, the machine gun would have to spit bullets frame after frame until the nextFireTime reached the current time. To avoid this, the second if resets nextFireTime to a little before the current time when more than fireRate seconds have elapsed since the last shot.

A simpler approach would be to add fireRate to the current time when shooting:

  if (nextFireTime <= Time.time && bulletsLeft > 0){
    FireOneShot();
    nextFireTime = Time.time + fireRate;
  }

The fire rate in the first method is a little more precise because it doesn’t accumulate time errors (what doesn’t make much difference at all).

NOTE: The explanation above only considers fire rates lower than the frame rate. @syclamoth noticed an interesting feature of the first method: it allows fire rates greater than the frame rate, and that’s why nextFireTime is set to the previous frame time when start shooting.