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 check if the player is holding a key down?

I know how to check if the player pushes a key down, but I'm not sure how to check it is is being held down. The code below is how I check if it has been pressed, but not held down.

--This will jolt the player in the direction that they are facing when they push W.
function OnPressW(actionName, userInputState, inputObject)
	if userInputState == Enum.UserInputState.Begin then
		script.Parent.HumanoidRootPart.BodyForce.Force = 				 
                Functions.GetRotation(player.HumanoidRootPart) * Vector3.new(0,0,1) * -40000;
	end
end
game.ContextActionService:BindAction("OnPressW", OnPressW, false, Enum.KeyCode.W)

4 comments

1

i just hook userinputservice and set a variable to true/false when the InputBegan/InputEnded completes

0

I've heard that you're supposed to use ContextActionService instead for some reason.

1

^ you don't have to use ContextActionService but it makes it easier for making multi-platform games you can bind certain inputs from different platforms to a function

0

oh

1 answer

✓ Accepted answer

Hi. In order to know when the player is holding the key down, you need to.make a variable that you're going to set to true when the key is pressed, and to false when its released using InputBegan and InputEnded events of UserInputService.

local wDown = false
local uis = game:GetService("UserInputService")
uis.InputBegan:Connect(function(iobj, gp)
    if gp then return end --abort if they are i.e. typing in a textbox
    if iobj.KeyCode == Enum.KeyCode.W then
        wDown = true
        while wDown do
            wait()
            print("w is down")
        end
    end
end)

uis.InputEnded:Connect(function(iobj, gp)
    if gp then return end
    if iobj.KeyCode == Enum.KeyCode.W then
        wDown = false
    end
end)

1 comment

0

thanks

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