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

How do I keep track of key presses in a table with UserInputService?

Asked by
Perci1 4988 Trusted Moderation Voter Community Moderator
9 years ago

WIth KeyDown, this was easy. But KeyDown doesn't work for every key and is now deprecated. Before, I could just do something like this:

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()
local pressed = {}

mouse.KeyDown:connect(function(key)
    pressed[key] = true
end)

And this would work because key is a string. Now I could just say pressed.q to check if q had been pressed.

But this isn't so for UsetInputService. With that, you get an Enum as the parameter, not a string. How could I do the same thing as I did with KeyDown, but with the UserInputService?

1 answer

Log in to vote
1
Answered by 9 years ago

You could add the value of the Name property of the EnumItem to the pressed table as an index and then you can just use pressed["Q"] to check if Q had been pressed.

So, to do what you want to do with UserInputService, you'd want to use the InputBegan **and **InputEnded events to set the key's pressed state and then use the KeyCode property and the KeyCode EnumItem's Name property to set the key pressed as the index to the boolean pressed value.

local uis = game:GetService("UserInputService") --Get the UserInputService.
local pressed = {}

uis.InputBegan:connect(function(input)
    pressed[input.KeyCode.Name] = true --Set the Name property's value of the KeyCode EnumItem to true.
end)

uis.InputEnded:connect(function(input)
    pressed[input.KeyCode.Name] = false --Set the Name property's value of the KeyCode EnumItem to true.
end)

I hope my answer helped you. If it did, be sure to accept it.

0
Totally forgot about the Name property, thanks. Perci1 4988 — 9y
0
No problem. Spongocardo 1991 — 9y
Ad

Answer this question