Get time duration in key down event
Posted: Sun Jul 20, 2014 7:24 am
Can I get the time of duration for keydown event? I just want to find a way to distinguish between keypressed and keydown event.
Code: Select all
keys = {}
keyt = {}
function love.update(dt)
for k,v in pairs(keys) do
if v == 'pressed' and love.keyboard.isDown(k) then v = 'held' else
if v == 'released' and not love.keyboard.isDown(k) then v = 'free' end
-- and if you want to record how long the key is being held down, then:
if v == 'held' then
if keyt[k] ~= nil then
keyt[k] = keyt[k] + 1 -- or dt if you want time instead of ticks
else
keyt[k] = 1 -- or dt, see above.
end
end
end
function love.keypressed(key)
-- i'm fairly certain i had at least a decent reason for doing the thing below this way, else a simple keys[key] = 'pressed' would suffice.
if keys[key] == 'pressed' then
keys[key] = 'held'
else
keys[key] = 'pressed'
end
end
function love.keyreleased(key)
-- i'm fairly certain i had at least a decent reason for doing the thing below this way, else a simple keys[key] = 'released' would suffice.
if keys[key] == 'released' then
keys[key] = 'free'
else
keys[key] = 'released'
end
end
Why not just store the time when the key is pressed and use that to find the difference when the key is released?zorg wrote:you can do something like this (my original usage was that i needed to differentiate between 4 key states):
Code: Select all
keys = {}
function love.keypressed(key)
keys[key] = os.clock()
end
function love.keyreleased(key)
keys[key] = os.clock() - keys[key]
end
Code: Select all
function getHeldTime(key)
if love.keyboard.isDown(key) then
return os.clock() - keys[key]
else
return keys[key]
end
end