I am making a simple tower defense game and right now I’m working on a reload mechanism in the game. I want a reload delay so this is the reload function I’ve come up with:
function reload(self)
sleep(0.6)
self.ammo = self.maxAmmo
msg.post(“hud”, “update”, {ammo = self.ammo, maxAmmo = self.maxAmmo})
print(“Reloaded!”)
end
My problem is with the sleep() function.
function sleep(n)
local t = os.clock()
while os.clock() - t <= n do
– Nothing
end
end
Whenever i run the sleep() function, the whole game freezes, for the determined time when running the function.
As you might understand, I don’t want the whole game to freeze during reload, is there anything I can do to fix this?
Either if you have another function I could use or is there any way I can modify my current one?
local timer = require ("main.timer")
function reload()
print("Reloaded!")
end
function init(self)
timer.seconds(2, reload)
end
function update(self, dt)
timer.update(dt)
end
The problem with your sleep function is that you are busy-waiting for the required time to elapse. While you’re in the while-loop the engine will not continue to render more frames and execute other scripts etc.
Using something like the timer module pkeod posted will allow you to postpone a function call for a certain period of time without blocking execution. You could also do a dummy go.animate() call with a callback.