Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 4 years ago

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

Log in to vote
3
Answered by
k3du53 162
4 years ago
Edited 4 years ago

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

Ad

Answer this question