Is their a way to check if a player Holds Down a Key with UserInputService?

HellO! I just started learning User input service but the thing is that I want it check if the player is holding down a computer key

3 Likes

https://developer.roblox.com/en-us/api-reference/function/UserInputService/GetKeysPressed

local UIS = game:GetService("UserInputService")
local allKeys = {}

UIS.InputBegan:Connect(function(input, process)
	if process then return end
	
	allKeys[input.KeyCode] = true
end)

UIS.InputEnded:Connect(function(input, process)
	if process then return end

	allKeys[input.KeyCode] = false
end)


while wait() do
	if allKeys[Enum.KeyCode.LeftShift] then
		print("Is holding the leftShift")
	else
		print("Is not holding the leftShift")
	end
end
2 Likes

Do a while loop while the player is holding the key you want

Try UserInputService:IsKeyDown()

9 Likes

What you could do is run an if statement for the key and check if its down using :IsKeyDown(), like such:
(UserInputService | Roblox Creator Documentation)

local UIS = game:GetService("UserInputService")
local MyKey = Enum.KeyCode.[Insert your key]

UIS.InputBegan:Connect(function(input,gameProcessed)
	if gameProcessed then return end

	if input.KeyCode == MyKey then
		print(key, "was pressed")

		while UIS:IsKeyDown(MyKey) do wait()
			print(key, "is still down")
		end
		
	end
end)

oops I didn’t see somebody else already said the same thing, my bad

7 Likes

@DuckingDucky, it didn’t seem to work

UIS:IsKeyDown(Enum.KeyCode.J):Connect(function(input, gameProccessedEvent)
	local HumanoidRootPart = script.Parent:FindFirstChild("HumanoidRootPart", true)
	local Force = Instance.new("BodyVelocity")
	Force.Name = "Jump"
	Force.Parent = HumanoidRootPart
	Force.Velocity = 1000
end)

The reason it didn’t work is because it returns a bool value, it doesn’t activate an event when the key is pressed. Try the script I posted above

can you explain to me how the code works? its confusing

Sure (again sorry I don’t explain things, I often forget). So when you call UIS:IsKeyDown(), it’s asking (basically) “is this key (in the () ) down?” And if the key is down, then it will return true and if it’s not down it returns false. So, in my script where I say while UIS:IsKeyDown(MyKey) do, it’s asking “is this key down” each time the loop is iterated; and if it’s down the loop will continue, and if the key isn’t down the loop will stop.

The reason this doesn’t work is because the function :IsKeyDown() is a function, not an event, which means that it doesn’t actually ‘fire’ anything, unlike .InputBegan or .InputEnded.
What that line of code is essentially saying is " true (--or false):Connect(function(input, gameProcessedEvent ." Hope that helped clear things up

Note: while UIS:IsKeyDown(MyKey) do is the same as while UIS:IsKeyDown(MyKey) == true do

replace first line with if UIS:IsKeyDown(Enum.KeyCode.J) then
and remove “)” on the last line

1 Like