How to check if a key is being Pressed or Holded

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
2 Likes

Please use the search, there are tons of posts with this question.

None solved my problem either :confused:

1 Like

Search up UserInputService.

30

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
7 Likes

Let me clearify what i need, i know UIS and all that stuff.

I want a function that returns a value meaning they holded for a lil bit or another value if they holded for more time

i.e function that returns if they holded for a bit or holded a lil more

yeah ill search UIS in depth too.

That’s what the final code sample does, you need to define what “held for a little bit” means though, which I set as 0.5 at the top of that sample.

You can call isKeyBeingPressed when you need to find if a key is being held.

a lil bit i mean is lesser than the holdThreshold, basically pressing.

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.