I’m trying to use a timer, etc. to require a button to be pressed by not released for X seconds and if released before that time it doesn’t fire it’s event.
I’m coming up short – anyone got any dead simple code/example of how to do it?
I’m trying to use a timer, etc. to require a button to be pressed by not released for X seconds and if released before that time it doesn’t fire it’s event.
I’m coming up short – anyone got any dead simple code/example of how to do it?
This will print “Success!” if the player holds down some_button
for 5 seconds:
function on_input(self, action_id, action)
if action_id == hash("some_button") then
if action.pressed then
self.timer = timer.delay(5, false, function() print("Success!") end)
elseif action.released then
timer.cancel(self.timer)
end
end
end
There are two main ways to do this @Potota posted the timer way, but you could also use delta time coming from the update function. (This second way is more if you need to have how long they’ve been holding down for some button animation or something, if you don’t need that going with the timer method is a lot simpler )
local elapsed = 0
local target_time = 2
function update(self, dt)
if self.holding then
elapsed = elapsed + dt
if elapsed > target_time then
self.holding = false
elapsed = 0
print("Held long enough!")
end
end
end
function on_input(self, action_id, action)
if action_id == hash("button_press") then
if action.pressed then
self.holding = true
elseif action.released then
self.holding = false
elapsed = 0
end
end
end
Third solution. Track time when button was pressed and released:
function on_input(self, action_id, action)
if action_id == hash("some_button") then
if action.pressed then
self.pressed_time = socket.gettime()
elseif action.released then
if (socket.gettime() - self.pressed_time) > 5 then
print("Success!")
end
end
end
end
Thank you everyone! I used @Potota approach and it’s working nice. One thing I think happens is that if you hold the selection after and it’s part of a loop of actions (think like a conversation tree) and they release their input AFTER the timer has itself finished executing you can throw an error on the action.released element of canceling a timer that’s completed. So I added:
if self.timer ~=nil then timer.cancel(self.timer) end
So that it cancels only a timer that itself is still executing when the user releases. That has so far stopped the errors I was seeing, and not introduced anything newly problematic… yet.