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

How do I make a localscript recognize when I've pressed a key?

I'm ultimately trying to make a localscript that prevents the player from using the W and S keys to move forward and backward (platform game). For now, though, I'm trying to get the concept of just getting a script to recognize when these keys are pressed. My goal with this specific script is to make it print "q off" and "q on" when I press the Q key.

I probably did this all wrong because I'm new to Lua, but I gave it my best shot. No error messages, but it doesn't work. The following code is in a local script.

local player = game.Players.LocalPlayer
deb = false
input = game:GetService("UserInputService")
actionkey = Enum.KeyCode.Q

function pressQ(key)
	if key == actionkey and deb == false then
		print("q on")
		deb = true
	end
	if key == actionkey and deb == true then
		print("q off")
		deb = true
	end
end

input.InputBegan:Connect(pressQ)

Thanks for any help!

1 answer


InputObjects


The first parameter of InputBegan is the input object, which isn't a keycode enum. However, it does have a KeyCode Property that can be used for this purpose.

local player = game.Players.LocalPlayer
local deb = false
local input = game:GetService("UserInputService")
local actionkey = Enum.KeyCode.Q

local function pressQ(key,gpe)
	if gpe then return end
	if key.KeyCode == actionkey  then
		if deb then 
			print("q off")
			deb = false
		else
			print("q on")
			deb = true
		end	
	end
end

input.InputBegan:Connect(pressQ)

Some other minors things here:

  • You didn't change deb back to false after checking if it was true, thus it will always print "q off"

  • you should really use local variables here

  • InputBegan has a 2nd parameter , that is the game processed event boolean, which is true if the key has been used for something else before that specific InputBegan event. It can be used to tell whether if the player in question is typing (one example of how it can be used)

5 comments

0

I made the changes you suggested (thanks so much), but it's still not working when I test it in Studio. Any ideas?

0

hmm

0

there might be other factors at play here

0

try using remote events

0

MC, could you answer this question with an example of how to use remote events? I've never coded with one before.

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