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

How to assign a Keydown from a GUI?

Asked by 9 years ago

I don't understand how this is done could someone point me to the right direction?

1 answer

Log in to vote
1
Answered by 9 years ago

The KeyDown event fires when the players mouse pushes down on a key. To get the mouse we need to use the :GetMouse() function. And do use that function we need to get the player. We get the player by using LocalPlayer which only works in a local script.


First we need to get the player using LocalPlayer which can only be used by a LocalScript. LocalPlayer would be in Players which is in game. This is what the script should look like:

local player = game.Players.LocalPlayer --LocalPlayer is in Players.
--or
local player = game:GetService("Players").LocalPlayer --These 2 are exactly the same.

Now the mouse we get by using the function :GetMouse(). This function came out in 2010 to help people get the players mouse. Now it should look like this:

local player = game.Players.LocalPlayer
local mouse = player:GetMouse() --Lua is CASE SENSITIVE.

Now for the KeyDown event. This is the event of the mouse. The KeyDown event has one parameter. Which is what key the player pressed. Now with that knowledge it should look like this:

local player = game:GetService("Players").LocalPlayer
local mouse = player:GetMouse()

mouse.KeyDown:connect(function(key)
    print("The player has pressed the "..key.." button!")
end)

If you pressed "h" It will print:

The player has pressed the h button!


Now we can see if the key he pressed is a certain key on the keyboard. For instance:

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

mouse.KeyDown:connect(function(key)
    if key == "h" then --If they pressed h then
        print("The player has pressed the h button!")
        else
        print("The player has NOT pressed the h button.")
    end
end)

Now lets say you want them to press the Left Shift button. You can't just put

key == "Left Shift"

It would error. We would use something called string.byte(). The script would look like this:

local player = game:GetService("Players").LocalPlayer
local mouse = player:GetMouse()

mouse.KeyDown:connect(function(key)
    if key.byte() == 32 then --If they pressed h then
        print("The player has pressed the Space button!")
        else
        print("The player has NOT pressed the Space button.")
    end
end)

The number "32" means space in Dec. The chart is here. Look for space. The number you want to use is under "Dec".


I hope this helped!

0
Thanks :D Relampago1204 73 — 9y
0
You're welcome Also please accept my answer! You also get reputation when you accept answers! This would be helpful because you have -3 rep :C EzraNehemiah_TF2 3552 — 9y
Ad

Answer this question