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

Is there a way to detect if a player pressed a key?

Asked by 10 years ago

Hello, as the title says, I want to know if it is possible to detect if a certain player presses a key (e.g. The "Q" key), and then run a script using it. I have searched in a lot of sources, but I can't find any way to do it. Could someone please help me?

I want to use this script for my RTS project I'm working on, so I only need the listener/connector, and then I'll do the rest of the script alone.

Thanks in advance,

mranderson11

2 answers

Log in to vote
2
Answered by
Azarth 3141 Moderation Voter Community Moderator
10 years ago

Check out the KeyDown event.

local player = game.Players.LocalPlayer
    -- You have to use a local script to use the player's mouse and or keys. 
local mouse = player:GetMouse()
    -- GetMouse() method

mouse.KeyDown:connect(function(key)
    -- Anonymous function with 'key' being whatever you pressed. 
    if key:upper() == "Q" then 
        -- Compare
        print("Correct key was pressed")
    else
        print("Try again")
    end
end)

-- Holding version

local player = game.Players.LocalPlayer
    -- You have to use a local script to use the player's mouse and or keys. 
local mouse = player:GetMouse()
    -- GetMouse() method
local needed = "Q"
    -- Your key
local down = false



mouse.KeyDown:connect(function(key)
    -- Anonymous function with 'key' being whatever you pressed. 
    if key:upper() == needed then 
        -- Compare
        down = true
       repeat print("Holding the key") wait() until not down
        print("You let go!")
    else
        print("Try again")
    end
end)

mouse.KeyUp:connect(function(key)
    if key:upper() == needed then 
        down = false
    end
end)

0
Does that script check when someone holds a mouse button AND presses a key, or only when it presses the key? TheArmoredReaper 173 — 10y
0
Nevermind, just checked the Wiki for that event. Thanks! TheArmoredReaper 173 — 10y
Ad
Log in to vote
0
Answered by 10 years ago

@ Azarth - How would someone make it check key:upper and lower?

0
Key:upper() makes it so any time a key is pressed, it changes it to its upper case style. So if you use Key:upper() and press q, the script will take the q and change it into a Q, thus making it easier to check for a letter as there's only one style. TheArmoredReaper 173 — 10y
0
Oh, thanks! Champion121212 22 — 10y

Answer this question