1 | function onKeyPress(inputObject,gameProcessed) |
2 | if inputObject.KeyCode = = Enum.KeyCode.V then |
3 | --do stuff |
4 | end |
5 | end |
6 | game:GetService( "UserInputService" ).InputBegan:connect(onKeyPress) -- an event for buttons on keyboard |
using this event, along with a key event, only sends it once, when the inputObject is pressed. I am aiming for the user to hold down a button, but there is not options for it at all. I have tried while loops, ends up crashing, I also have tried using isKeyDown, which only tells me if the key is part of the keyboard...
One method could be to add a debounce and a while loop, for example when you press the button you change the debounce to true and when the button is released, make it false. Then all you have to do is use a while debounce == true do loop.
01 | KeyHeld = false |
02 |
03 | function onKeyPress(inputObject,gameProcessed) |
04 | if inputObject.KeyCode = = Enum.KeyCode.V then |
05 | KeyHeld = true |
06 | while KeyHeld then |
07 | --do stuff |
08 | wait() |
09 | end |
10 | end |
11 | end |
12 |
13 | function onKeyRelease(inputObject,gameProcessed) |
14 | if inputObject.KeyCode = = Enum.KeyCode.V then |
15 | KeyHeld = false |
16 | end |
17 | end |
18 |
19 | game:GetService( "UserInputService" ).InputBegan:connect(onKeyPress) |
20 | game:GetService( "UserInputService" ).InputEnded:connect(onKeyRelease) |
This is how I've been using controls for my games:
01 | local tabDown = false |
02 | local input = game:GetService( "UserInputService" ) |
03 | local player = game.Players.LocalPlayer |
04 |
05 | input.InputBegan:connect( function (k) |
06 | local key = k.KeyCode |
07 | if key = = Enum.KeyCode.Tab then |
08 | tabDown = true |
09 | end |
10 | end ) |
11 |
12 | input.InputEnded:connect( function (k) |
13 | local key = k.KeyCode |
14 | if key = = Enum.KeyCode.Tab then |
15 | tabDown = false |
It works very well for me. Of course in your case you would have to change the Enum for the key but other than that it should work.