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

How should I detect keys that are pressed?

I have been using a key script in my game, and it seems to work pretty well, only that the method I am using can't seem to tell the difference between key 0 and shift, and the Ctrl key and 2. This is quite frustrating as I have a secondary weapon on key two and an ability on the Ctrl key. So whenever someone takes out their secondary, they end up using their ability as well. Also when they hold 0 they sprint, but mainly the problem is the Ctrl key. The method I am using (It might be decrepit or something idk) is this:

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


mouse.KeyDown:connect(function (key) -- Run function

	key = string.lower(key)
	print (string.byte(key))
	if string.byte(key) == 50 then -- supposed to be Ctrl, but activates on 2 as well
		--do stuff
	end
end)

How do I distinguish between 2 and CTRL? Thanks in advance for your help.

3 comments

0

Don't use KeyDown. That is deprecated in favor of UserInputService and ContextActionService.

0

Also why string.byte?

0

ok I will switch to that

1 answer

✓ Accepted answer
local UserInputService = game:GetService("UserInputService")

UserInputService.InputBegan:Connect(function(Input)
	print(Input.KeyCode)
	if Input.KeyCode == Enum.KeyCode.LeftControl then
		--Do Stuff
	end
end)

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