Page 1 of 1

Get time duration in key down event

Posted: Sun Jul 20, 2014 7:24 am
by herksaw
Can I get the time of duration for keydown event? I just want to find a way to distinguish between keypressed and keydown event.

Re: Get time duration in key down event

Posted: Sun Jul 20, 2014 9:13 am
by Plu
Not by default. You'd have to measure it yourself.

But why do you want to distuinguish? They're two different functions, they can't really be confused.

Re: Get time duration in key down event

Posted: Sun Jul 20, 2014 8:28 pm
by zorg
you can do something like this (my original usage was that i needed to differentiate between 4 key states):

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

Re: Get time duration in key down event

Posted: Sun Jul 20, 2014 8:55 pm
by Lafolie
zorg wrote:you can do something like this (my original usage was that i needed to differentiate between 4 key states):
Why not just store the time when the key is pressed and use that to find the difference when the key is released?

Re: Get time duration in key down event

Posted: Tue Jul 22, 2014 10:47 am
by zorg
Well then,

Code: Select all

keys = {}

function love.keypressed(key)
    keys[key] = os.clock()
end

function love.keyreleased(key)
    keys[key] = os.clock() - keys[key]
end
Though you'd need to check for the key to not be pressed since this only gives back the correct held time then...unless you use something like this:

Code: Select all

function getHeldTime(key)
	if love.keyboard.isDown(key) then
		return os.clock() - keys[key]
	else
		return keys[key]
	end
end

Re: Get time duration in key down event

Posted: Wed Jul 23, 2014 6:18 pm
by Lafolie
See how little code there is compared to the first version? :)