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

Help with equiping tools using keydown events?

Asked by
xTalzo 10
9 years ago

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?

2 answers

Log in to vote
0
Answered by
ImageLabel 1541 Moderation Voter
9 years ago

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.

01local player = game:GetService("Players").LocalPlayer
02local uis = game:GetService("UserInputService")
03local key = "R" -- key to bind
04local time = os.time()
05 
06local character = player.Character or player.CharacterAdded:wait()
07 
08uis.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
19end)
Ad
Log in to vote
3
Answered by 9 years ago

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:

1local player = game:GetService("Players").LocalPlayer
2local mouse = player:GetMouse()
3 
4mouse.KeyDown:connect(function(key)  -- The "key" is what the user pressed
5    if key:lower()=="q" then
6        print(key.." was pressed")
7    end
8end)

Now, if you're looking for double pressing space bar, you could use some debounce method as such:

01local player = game:GetService("Players").LocalPlayer
02local mouse = player:GetMouse()
03 
04local between = 0.5 -- Time in which double tap is needed (in seconds)
05local double = false
06 
07mouse.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
17end)

Answer this question