How to use UserInputService to detect a change in input

I want to kick the player if they click a button too many times, like “spacebar” 100 times in a row, or move them to a certain spot.
Sadly I don’t understand how to detect the change or my brain just isn’t registering what I need to do.
Local script in starterplayerscript:

local userInputService = game:GetService("UserInputService")
local player = game.Players.LocalPlayer

userInputService.InputBegan:Connect(function(input, gameProcessed)
	if gameProcessed then return end
	if input.UserInputType == Enum.UserInputType.Keyboard then
		local inputType = input.UserInputType
		local input = input.KeyCode
		game.ReplicatedStorage.RemoteEvents.UserInputRemotes.UserInput:FireServer(input, inputType, player)
	end
end)

The second script is my server script:

local replicatedStorage = game:GetService("ReplicatedStorage")
local Remotes = replicatedStorage:WaitForChild("RemoteEvents")
local userInputEvent = Remotes:WaitForChild("UserInputRemotes")
local count = 0

userInputEvent.UserInput.OnServerEvent:Connect(function(player, input, inputType)
	print("event for user input fired")
	print(input)
	print(inputType)
	if input == input then
		count = count + 1
		print(count)
		if count >= 10 then
			player:Kick("You've been kicked to many identical attempts")
		end
	end
end)

My only real problem is that I can see it printing the different keycodes but how do I make it stop the count and start it again? If I make a local variable it always assigns the keycode from the localscript in the remote event to that keycode, so the server will always see them matching.

1 Like

You can make use of InputBegan to detect when the player holds down a key. When they release it, InputEnded will fire. Since pressing a key and then pressing it again only counts for one release, and two presses, the best thing to choose is InputBegan.
You can then have a code that stores the previous input, and the max number of times they can press that input in a row.

local uis = game:GetService("UserInputService")

local pKey = nil
local mCount=10
local count = 0

uis.InputBegan:Connect(function(inp,gpe)
	if not gpe then -- checks if the game processed the event or not
		if inp.KeyCode==pKey then
			count+=1
			if count>=mCount then
				--execute your code here
				
			end
		else
			count=0
		end
		pKey=inp.KeyCode
	end
end)
1 Like

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