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

How can I let the script know when the player has held down a key for a certain amount of time?

So I was creating a parkour script, and I wanted to play a panting audio when the player has held down LeftShift or RightShift for around 5 seconds.

I use UserInputService, and I don't know many forms of Input functions. The nearest I could find was IsKeyDown.

Here's my script, if you would like to polish it.

local UIS = game:GetService("UserInputService")

local RunningSound = 'rbxassetid://4518544160'
local WalkingSound = 'rbxassetid://156659098'
local running = script.Parent.HumanoidRootPart:WaitForChild("Running")

running.SoundId = WalkingSound
running.Pitch = 1.5

UIS.InputBegan:Connect(function(keyCode)
	if keyCode.keyCode == Enum.KeyCode.LeftShift or keyCode.keyCode == Enum.KeyCode.RightShift then
		running.SoundId = RunningSound
	end
end)

Now, I'm not asking for scripts or anything. I just want to learn a method of detecting when the player's key is being held down.

Help please!

1 answer

✓ Accepted answer

You can combine checking for key down and key up with an update loop that keeps track of the time the key has been held to do what you need. Something like this:

local UIS = game:GetService("UserInputService")
local RunService = game:GetService("RunService")

local RunningSound = 'rbxassetid://4518544160'
local WalkingSound = 'rbxassetid://156659098'
local running = script.Parent.HumanoidRootPart:WaitForChild("Running")

running.SoundId = WalkingSound
running.Pitch = 1.5

-- Variables used to detect key being held down
local isShiftDown = false
local keyDownTime = 0
local triggerTime = 5 -- Seconds that shift needs to be held

RunService.Heartbeat:Connect(function(step)
	-- While shift is held, increment keyDownTime and check if we exceed triggerTime
	if isShiftDown then
		keyDownTime = keyDownTime + step
		if keyDownTime >= triggerTime then
			-- Shift has been held for >= triggerTime. Change sound id
			running.SoundId = RunningSound
			
			-- Reset isShiftDown so that the code here doesn't keep firing while shift is held
			isShiftDown = false
		end
	end
end)

UIS.InputBegan:Connect(function(input, gameProcessed)
	if input.KeyCode == Enum.KeyCode.LeftShift or input.KeyCode == Enum.KeyCode.RightShift then
		-- Shift is held
		isShiftDown = true
	end
end)

UIS.InputEnded:Connect(function(input, gameProcessed)
	if input.KeyCode == Enum.KeyCode.LeftShift or input.KeyCode == Enum.KeyCode.RightShift then
		-- Shift is released
		isShiftDown = false
		keyDownTime = 0
	end
end)

1 comment

0

Tysm! This helped me SOOOO much!

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