How to set cooldown timer on shooting function?

I was wondering how I could place a cooldown on a function so that when the game is built, one player cannot spam the button to rapidly shoot.

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

I do this all the time with my alarm function. I believe Defold is going to have itā€™s own built-in timer function in the near future?

@klu2022, hereā€™s the code if you want it.

function Alarm(alarm)
	if alarm.endT == nil then
		alarm.endT = 0
	end
	
	if alarm.endT == 0 then
		alarm.endT = os.clock() + alarm.time
	elseif os.clock() >= alarm.endT then
		if alarm.name ~= nil  then
			print("ALARM_FIRED: " .. alarm.name)
		end
		alarm.endT = 0
		return true
	end
end

This alarm must be run on Update so that it checks the timing every frame, otherwise it just stops. Feed it a table like this:

local myAlarm = {name = "myAlarm", time = 1}
-- time is in seconds. Lower frame rates have lower precision,
-- while higher frame rates have higher precision.

function Update(self, dt)
     if Alarm(myAlarm) == true then
          print("My alarm has fired")
     end
end

I feel that using a full-blown timer system is overkill here, and might actually serve to make some usecases harder to implement (ticking a timer forward by some large amount of time other than the standard tick length, using different intervals based on the reload skill of the character or reload difficulty of the current weapon, etc.).

@britzlā€™s example, on the other hand, is very flexible and easily implements cases like that (by, for example, changing the socket.gettime() call to a counter ticking away in some update(self,dt) function and handling self.last_shot in various ways).

In either case, a beginner will probably have an easier time understanding and expanding on the more straightforward approach rather than a system where some of the technicalities are hidden away.

3 Likes

Yep, definitely overkill. I agree with @britzlā€™s approach. I just wanted to supply it in case there were any other uses for it (like if you had several different scripts running individual alarms). In that case, this would keep things neater and make it a bit easier to implement all of them.

1 Like

I used @britzlā€™s approach, and tweaked it a little. I have a question: what does the ā€œprintā€ function do?

ā€˜printā€™ prints whatever string is placed between its parentheses into the console window below the editor window. It is primarily used for bug testing or testing out new features without programming the full thing (like writing ā€œBANGā€ whenever a gunshot would be fired - actually programming a bullet firing just to test a timer seems excessive).

ā€˜printā€™ is a Lua function, and since Defold exclusively (well) uses Lua, you might want to check it out. There are many excellent tutorials available online to familiarize yourself with the language, or you can check out the tutorial available at the Lua programming in Defold, which is more geared towards how Lua might be used in Defold.

2 Likes

Ok thanks! Iā€™ve been working on my project, and on the console there have been ā€œMalformed messagesā€. I donā€™t think anything has been drastically off, and there are no bugs.

What do you mean by ā€˜malformed messagesā€™? Is that the exact output, or does it just look strange?

If you want to send the script file over for me to take a look at, feel free to do so, or you can post the code here, if it is short enough.

1 Like

I zipā€™d the file, but itā€™s not uploading onto the forum. After choosing and ā€œopeningā€ the file, the upload percentage starts at zero and then disappears. There is nothing on the post, as the forum says its empty.

print isnā€™t a lua specific function, it can be used in many languages actually. ā€œprintā€ is just telling the console to write out something the same way you could say console.writeline(ā€œIā€™m writing whatever I want just like saying print in luaā€), DART would be main(){print(ā€˜now iā€™m writing in another programming languageā€™);} and so on i could find you many examples or you can just look them up. anyways ā€œprintā€ in general is extremely useful when coding in games specifically because you can print out what you want to do and organize your thoughts so that you can start working on a code that does what the messages printed out are saying. I just recently started using it from watching them do it on the tutorial videos on youtube and it really helps a lot like when you are stuck starting out a code and donā€™t know to much about coding just write out print this and run your game and if it prints when something happens that you wrote it to then you know ok now instead of print lets try this and so on until it works!

Thatā€™s strange. Feel free to email it to me at cfnb@st-andrews.ac.uk, if you want, and I can take a look at it when I have the time.

Indeed, ā€˜printā€™ in some form or another certainly isnā€™t unique to Lua. Most programming languages will have some variant implemented.

Yes, printing can be very valuable as a high efficiency way to test out things, and will often save a lot of time when building up the core mechanics of a game.

2 Likes

Well, yes, most languages have a means to output text to standard out. In Lua it happens to be using the print() function or io.write(). In other languages it is ā€˜echoā€™, or ā€˜System.out.println()ā€™ or ā€˜printf()ā€™ or some other function, but the end result is the same.

Not to be rude but some people like me may understand it different, and if you are coming from a different language such as me it comes off as confusing so i wanted to make it clear that print can be used and how it should be used from any language in general as to just assuming that the person knows LUA specifically @britzl I just feel some people arenā€™t as program savvy as others and that is why they come here for help but arenā€™t always greeted with the warmest of welcomes unless they know anything about programming but yall donā€™t welcome anyone that hasnā€™t had a chance to even learn

Iā€™m sorry if you feel that way. That was not my intention.

I didnā€™t mean to be rude and I understand you probably get a lot of the same questions that are really simple to you and shouldnā€™t seem like you need to explain, but sometimes itā€™s like oh you donā€™t know that you should know that! and itā€™s like thatā€™s exactly why these questions are asked because we need someone like you and iā€™m sure there are plenty of people on here that do know what they are talking about and have questions that arenā€™t easy ones wasting your time that you could be better off answering

I think you might be reading hostility into @britzlā€™s comment where there is none. I also consider it natural to discuss any functions in Defold from the viewpoint of Lua, as all programming in Defold is done in Lua.

The forums are for all kinds of questions - thatā€™s exactly the purpose of this part of the forum. If I considered answering questions of any kind a waste of my time then I would not answer them - but I do answer them.

1 Like

I wasnā€™t reading any hostility I am way cool, itā€™s just I have previously asked a question before on one of my topics and at first i was answered ā€œyou really need to learn programming basics, read the manualā€ after i already had read the manual and do somewhat know programming basics(not a pro or close to one) but I was asking a question because i was confused and didnā€™t have a classroom atmosphere like I usually do with a teacher and students around me. So it was more of constructive criticism to help improve community for everybody. we ended up fixing what i asked tho im pretty happy with the game he really helped me out and explained array usage in LUA because i come from C# so that was throwing me for a loop lol

2 Likes

as other said, there isnā€™t any kind of wait function (atm) in defold, but itā€™s not a big deal to create one.

local isWaitOver = false

function wait(waitTime)
	isWaitOver = false
	waitStart = os.time()
	waitEnd = waitStart + waitTime
	while waitEnd ~= os.time() do
		isWaitOver = false
	end
	isWaitOver = true
end