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

How Would You Go About Detecting a Double-Tapped Key?

I have made keybindings that play an animation when held down or tapped, but how would I go about detecting whether or not a key ('w' for instance) is pressed twice in quick succession? I have seen many games do this where double-tapping 's' will make you do a backflip or something, so I know this is possible. Here is some code that I use for my current key-bindings if it helps at all:

m.KeyDown:connect(function(key)
	local player = game.Players.LocalPlayer
	local curr_stam = tonumber(player.PlayerGui.Stats.Frame.StaminaQuantity.Text)
	if key == "0" and curr_stam > 0 and game.Players.LocalPlayer.Character.Humanoid.WalkSpeed >= 16 then --"Shift to run" 0 == shift
		game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 50
	end
end)

m.KeyUp:connect(function(key)
	if key == "0" and game.Players.LocalPlayer.Character.Humanoid.WalkSpeed >= 16 then
		game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 16
	end
end)

1 comment

0

I'd recommend using UserInputService as KeyDown and KeyUp is deprecated

1 answer

✓ Accepted answer

You could add a variable that increases everytime the key is pressed, and when it reaches a certain number, the function activates.

local InputService = game:GetService("UserInputService")

local Num = 0

local function InputKey(Input, GameEvent)

	if GameEvent then return end

	if Input.KeyCode == Enum.KeyCode.Z then

		Num = Num + 1

		if Num == 2 then
			Num = 0
			--Your function here
		end

		wait(1) -- Sets to 0 after 1 second
		Num = 0

	end 

end

InputService.InputBegan:Connect(InputKey)

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