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

How do I execute a script when a key is held for some time?

Asked by
yurhomi10 192
10 years ago

So, I want to learn how to execute a chunk of code when a player presses and holds a key but i'm not sure how to approach this, any help?

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

mouse.KeyDown:connect(function(key)
    print(key:byte())
    if key == "f" then
        print("wassup")
    else
        print("hi")
    end
end)

1 answer

Log in to vote
3
Answered by
Asleum 135
10 years ago

All you have to do is use a while loop to keep track of the time the key has been pressed. You also have to detect when the key has been "un-pressed" to reset that time. Like this :

player = game.Players.LocalPlayer
mouse = player:GetMouse()
fPressed = false
timePressed = 0

mouse.KeyDown:connect(function(key)
    if key == "f" then
        fPressed = true
    end
end)

mouse.KeyUp:connect(function(key)
    if key == "f" then
        fPressed = false
        timePressed = 0
    end
end)

while true do
    if fPressed then
        timePressed = timePressed + wait()
        if timePressed > 3 then
            print("F has been held for three seconds")
        end
    else
        wait()
    end
end
0
Impressive, but when I stop holding after the '3 second mark' it continues back where it left off. Very appreciated though! yurhomi10 192 — 10y
0
One more thing, is there way to stop the 'spam' it causes when you have held the key for more then 3 seconds? yurhomi10 192 — 10y
0
To fix that, just add a protection on line 20 that checks if your function has already been activated. Or, at line 23, just reset timePressed and set fPressed to false ;) Asleum 135 — 10y
Ad

Answer this question