- Home /
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)
It's for guaranteeing that the correct number of bullets will always fire in a given frame, if the rate of fire is higher than the framerate. Simply, it resets the 'nextFireTime' to the previous frame if the shot should have happened several times this frame.
Good explanation, @syclamoth! I wasn't thinking about a fire rate greater than the framerate, what explains perfectly this code. I edited my answer, but only God knows when it will appear in the questions page.
Answer by aldonaletto · Mar 04, 2012 at 03:38 AM
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 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.
Your answer
Follow this Question
Related Questions
Where is the FPS Tutorial? 1 Answer
Learning about graphics in Unity 2 Answers
are animation frame dependent? 1 Answer
Complete AI Tutorial? 1 Answer
Where is the FPS Tutorial? 1 Answer