Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

✓ Accepted answer

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)

2 comments

0

Does that script check when someone holds a mouse button AND presses a key, or only when it presses the key?

0

Nevermind, just checked the Wiki for that event. Thanks!

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

2 comments

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.

0

Oh, thanks!

This discussion is preserved as it was. New answers, comments, and votes are closed.