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

How to detect when a player holds down a key(not just press)?

this is my code, its for a sprint button

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()

mouse.KeyDown:connect(function(key)
	if key == "r" then
		print("r Pressed")
		game.ReplicatedStorage.Events.stamniaEvent:FireServer(plr)
	end
end)

I know the code is gonna be a lot more than that so I need help and i haven't found anything really helpful on Youtube

1 answer

As far as I'm aware, using plr:GetMouse() to get the player's mouse has limitations and unfortunately, being able to check if the key is held down is one of those limitations.

One thing you can do is use the mouse.KeyDown event connected to a function that starts sprinting, then use mouse.KeyUp to stop sprinting. This is the faster way of answering your question. (But honestly, these are deprecated and you should totally be using UserInputService)

To do this with UserInputService, it would be something like:

game:GetService("UserInputService").InputBegan:Connect(function(input, gameProcessed)
	-- sprint!
	-- be sure to look at what gameProcessed means and does
end)

game:GetService("UserInputService").InputEnded:Connect(function(input, gameProcessed)
	-- walk!
end)

Relevant links that I think might help in some way:

UserInputService.InputBegan

UserInputService.InputEnded

UserInputService.IsKeyDown

Enum.KeyCode

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