How to Check the Time Between Two Tick Values?

I have been making a gun script and need a way to check if the time between the last shot and the present is over the fire rate of the gun.

I tried using a simple while loop and a wait as long as the fire rate. As you can also see I tried to use magnitude. Does magnitude work for tick() or am I writing the script wrong?

runService.Heartbeat:Connect(function()  
		if (lastShot - tick().magnitude) >= (60/FireRate) then
			-- Event
		end
	end)

You would just subtract the previous tick value and the current tick value. Magnitude doesn’t work for tick. Since the current tick value is always going to be larger than the previous tick value, you would subtract the smaller numer from the greater number, so it’ll be the current tick value minus the previous tick value.

Example:

local lastShot = tick();

runService.Heartbeat:Connect(function()
     print(tick() - lastShot)
end)

Another good way to do it: (os.time() is the same as tick() but in UTC)

startTime = os.time()
os.difftime(os.time(), startTime)

Unfortunately, os.time() only returns an integer so if you’re going for milliseconds then you’ll have to use tick().

1 Like