How to detect if a key is held

Hello, I’m working on a system where a lot of keys do different things, and to make my life easier I wanted to make it so that one key can have at least 2 functions, lets say just tapping G teleports me 10 studs but then holding it for 2 seconds, it teleports me 50 studs. How would I do that? I basically need to hold G, it does nothing until I let it go, or 2 seconds go by and it automatically does the second variant. Can someone give me a code example or tell me the function I need or just anything.

Any and all help means the world to me. I’m a solo dev doing everything so getting better at scripting goes a long way.

You can use the UserInputService and a script to detect whether the “G” key is tapped or held for a specific duration. Here’s a step-by-step guide:

local UserInputService = game:GetService("UserInputService")

local teleportDistance1 = 10  -- Distance to teleport when tapping G
local teleportDistance2 = 50  -- Distance to teleport when holding G for 2 seconds

local teleporting = false
local teleportStartTime = 0

local function handleInput(input)
    if input.UserInputType == Enum.UserInputType.Keyboard and input.KeyCode == Enum.KeyCode.G then
        if input.UserInputState == Enum.UserInputState.Begin then
            teleportStartTime = tick()
            teleporting = true
        elseif input.UserInputState == Enum.UserInputState.End then
            if teleporting then
                local elapsed = tick() - teleportStartTime
                if elapsed >= 2 then
                    -- Perform the action for holding G for 2 seconds (teleportDistance2)
                    print("Teleporting " .. teleportDistance2 .. " studs.")
                else
                    -- Perform the action for tapping G (teleportDistance1)
                    print("Teleporting " .. teleportDistance1 .. " studs.")
                end
                teleporting = false
            end
        end
    end
end

UserInputService.InputBegan:Connect(handleInput)
UserInputService.InputEnded:Connect(handleInput)

This code listens for keyboard input and checks for the “G” key. It measures the time the “G” key is held down and executes different actions based on whether it’s tapped or held for 2 seconds.

Replace the print statements with your actual teleportation logic or other game actions as needed. Good luck with your project!

2 Likes

Thank you so much for typing this out for me, means a lot to me

1 Like

No prob! Good luck with whatever you are doing!

2 Likes

Thank you, you too! Thanks again for your help

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.