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
11 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?

01player = game.Players.LocalPlayer
02mouse = player:GetMouse()
03 
04mouse.KeyDown:connect(function(key)
05    print(key:byte())
06    if key == "f" then
07        print("wassup")
08    else
09        print("hi")
10    end
11end)

1 answer

Log in to vote
3
Answered by
Asleum 135
11 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 :

01player = game.Players.LocalPlayer
02mouse = player:GetMouse()
03fPressed = false
04timePressed = 0
05 
06mouse.KeyDown:connect(function(key)
07    if key == "f" then
08        fPressed = true
09    end
10end)
11 
12mouse.KeyUp:connect(function(key)
13    if key == "f" then
14        fPressed = false
15        timePressed = 0
View all 28 lines...
0
Impressive, but when I stop holding after the '3 second mark' it continues back where it left off. Very appreciated though! yurhomi10 192 — 11y
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 — 11y
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 — 11y
Ad

Answer this question