How to set cooldown timer on shooting function?

There are many ways to do this. The easiest would be to store a timestamp when the last shot was fired and then not allow shots to fire to close to the previous one. Maybe like this (untested):

local SHOT_INTERVAL = 1.3		-- seconds

function init(self)
	self.last_shot = 0
end

function on_input(self, action_id, action)
	if action_id == hash("shoot") and action.released then
		-- get current time in seconds (with millisecond precision)
		local now = socket.gettime()
		
		-- shoot if the current time is more than the last time a shot was
		-- fired plus the minimum shot interval
		if now > (self.last_shot + SHOT_INTERVAL) then
			print("Bang! You're dead!")
			self.last_shot = now
		end
	end
end
4 Likes