For example, I have a tool, Fly, but I only want the player to access it if the double tap spacebar. How should I type the script?
An alternative to KeyDown
is UserInputService
. I had already helped you with something similar before so I won't go into too much detail as far as explaining goes. If you have any questions, comment on this reply and I will answer it in an edit.
01 | local player = game:GetService( "Players" ).LocalPlayer |
02 | local uis = game:GetService( "UserInputService" ) |
03 | local key = "R" -- key to bind |
04 | local time = os.time() |
05 |
06 | local character = player.Character or player.CharacterAdded:wait() |
07 |
08 | uis.InputBegan:connect( function (inputObject, processed) |
09 | if not processed then |
10 | if inputObject.KeyCode = = Enum.KeyCode [ key ] then |
11 | if (os.difftime(os.time(), time) < 0.8 ) then |
12 | warn( "double pressed" ) |
13 | -- clone tool into |
14 | -- player's inventory/ backpack |
15 | end |
16 | time = os.time() |
17 | end |
18 | end |
19 | end ) |
Use the KeyDown event given by the player mouse object. You can get this object by calling GetMouse() on the local player (in local scripts only)
Here's an example:
1 | local player = game:GetService( "Players" ).LocalPlayer |
2 | local mouse = player:GetMouse() |
3 |
4 | mouse.KeyDown:connect( function (key) -- The "key" is what the user pressed |
5 | if key:lower() = = "q" then |
6 | print (key.. " was pressed" ) |
7 | end |
8 | end ) |
Now, if you're looking for double pressing space bar, you could use some debounce method as such:
01 | local player = game:GetService( "Players" ).LocalPlayer |
02 | local mouse = player:GetMouse() |
03 |
04 | local between = 0.5 -- Time in which double tap is needed (in seconds) |
05 | local double = false |
06 |
07 | mouse.KeyDown:connect( function (key) |
08 | if key:byte() = = 32 then -- 32 is space bar |
09 | if double then |
10 | print ( "Double space" ) |
11 | else |
12 | double = false |
13 | wait(between) |
14 | double = true |
15 | end |
16 | end |
17 | end ) |