Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Is it possible to check if a player is holding down a key? (SOLVED)

Asked by 10 years ago

It sounds confusing I know, but read this to understand. I want to see that if a player holds down a key using the key: down event for 5 seconds, I want a action to happen. Is this even possible? And if so can you point me to the right direction?

2 answers

Log in to vote
0
Answered by 10 years ago

In a local script:

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

local down = {}

mouse.KeyDown:connect(function(key)
    --'tag' the time the key was pressed, set pressing to true
    down[key:lower()] = {pressing = true, tag = tick()}
end)

mouse.KeyUp:connect(function(key)
    --set pressing to false
    down[key:lower()] = {pressing = false, tag = 0}
end)

game:GetService("RunService").RenderStepped:connect(function()
    --loop through the keys
    for key, array in pairs(down) do
        --if the key is being pressed
        if array.pressing then
            print("\"" .. key .. "\" has been held for " .. tick() - array.tag .. " seconds.")
            if tick() - array.tag > 5 then
                print("ALERT: \"" .. key .. "\" has been held for more than 5 seconds!")    
            end
        end
    end
end)
Ad
Log in to vote
-1
Answered by
Muoshuu 580 Moderation Voter
10 years ago

Not very flexible and it can't tell if you let go and then re-held the key within the 5 seconds but it works...

local Key=nil
function KeyDown(K)
    Key=K
    wait(5)
    if Key then
        print(Key.." was held for 5 seconds")
    end
end
function KeyUp()
    Key=nil
end
0
Awesome thank you so much! GreekGodOfMLG 244 — 10y
0
I don't even think this would work. There aren't any events attached to the functions. Use mine, instead. ForeverDev 155 — 10y

Answer this question