Hello! How i can see if a key is being pressed or holded? I’m doing a fighting game where it does moves depending of how long you hold down a button, how i’d do it?
Example:
if IsPressed("F") then
-- do stuff
elseif IsHeld("F") then
--do other stuff
end
For buttons being pressed at a given time, use UserInputService:IsKeyDown(), :IsGamepadButtonDown(), and/or :IsMouseButtonPressed()
For buttons being held, you can do something like:
userInputService.InputBegan:Connect(function(input, gameProcessedEvent)
if gameProcessedEvent then return end
while userInputService:IsKeyDown(input.KeyCode) do
-- the button is being held
task.wait()
end
end)
Or if you need a function that you can call at a given time outside of the InputBegan connection, you can do something like this, you need to define how long you want the press to be before considering it a hold.
local holdThreshold = 0.5
local buttonsDown = {} -- buttons being held
userInputService.InputBegan:Connect(function(input, gameProcessedEvent)
if gameProcessedEvent then return end
local initTick = tick() -- time when the input started
while userInputService:IsKeyDown(input.KeyCode) do
buttonsDown[input.KeyCode] = tick() - initTick <= holdThreshold -- if the button has been pressed for longer than holdThreshold, it will detect as the button being held, setting the value to true
task.wait()
end
buttonsDown[input.KeyCode] = nil -- set to nil since entries in tables still take up memory
end)
local function isKeyBeingPressed(key)
return buttonsDown[key] == true -- will return true or false, we have to explicitly check if it's true, not just truthy because if the entry doesn't exist, it won't
end
Okay, then check the value of buttonsDown[some keycode].
If the value is nil, the key isn’t down at all, if it’s false, it’s down but is considered a short press, if it’s true, it’s down and considered a long press.