Input-detection function?

I’m wanting to make a function that once fired, detects movement inputs like W, A, S, D until something stops it (still figuring out what). In the end I want to make tile based movement that initiates after that function is fired. Does anybody have an idea on how I would go about this?

1 Like

You can use UserInputService :

UserInputService.InputBegan:Connect(function(Input, GameProcessedEvent)
    if Input.KeyCode == Enum.KeyCode.W then
        print("w pressed")

Or in a loop check if one of your input is pressed :


I know about UserInputService. My main confusion is how I can enable or disable the detection of those inputs at will if you know what I mean.

1 Like

Bool value? You can add an if statement in the input function and then have some way to make the value true or false somewhere in the script. If the value is false, it will disable the inputs and for true it will enable it.

1 Like

I don’t understand sorry you mean like disable player inputs ?

You can make the function return the connection that listens to keys so it can be disconnected after a certain timeframe/event:

local UIS = game:GetService("UserInputService")

function startDetecting(): RBXScriptConnection
	local validKeys = {"W", "A", "S", "D"}
	local connection = UIS.InputBegan:Connect(function(input)
		local key = input.KeyCode.Name
		if not table.find(validKeys, key) then return end
	return connection 

local connection = startDetecting()
print("Started listening")
print("Stopped listening")

Worked BEAUTIFULLY bro. Thanks all of you for your time!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.