Differentiate single key presses from double key presses?

I am attempting to make a basketball dribbling system, and would like to make it so that if you press Z once, it will do a Crossover however if you double tap Z, it will do a Sidestep.

I currently have this script:

local DRIBBLE_COMBOS = {
	["Threshold"] = 0.25,

	["LastZPress"] = 0,
	["ZPressed"] = false,
}


UIS.InputBegan:Connect(function(input, gp)
	if (input.KeyCode == Enum.KeyCode.Z) then
		local currentTime = tick()

		local function SinglePress()
			task.wait(DRIBBLE_COMBOS.Threshold)
			if (DRIBBLE_COMBOS.ZPressed) and not (DRIBBLE_COMBOS.DoubleTapped) then
				print("Crossover")
				DRIBBLE_COMBOS.ZPressed = false
			end
		end

		local function DoubleTap()
			DRIBBLE_COMBOS.ZPressed = false
			print("Sidestep")
		end

		if not DRIBBLE_COMBOS.ZPressed then
			DRIBBLE_COMBOS.ZPressed = true
			
			SinglePress()
		end

		if (currentTime - DRIBBLE_COMBOS.LastZPress) <= DRIBBLE_COMBOS.Threshold then
			DoubleTap()
		end

		DRIBBLE_COMBOS.LastZPress = currentTime
	end
end)

The issue is that it does detect double presses but also single presses. So the output looks like this when I double tap Z:

Crossover
Sidestep

If I double tap Z, it should only output Sidestep. Does anyone know how I can overcome this challenge? Thanks! :grin:

The problem is that the computer doesn’t know if you’re gonna do a single or double tap so you would have to wait the threshold time before doing the single press. You also have to store the new last tick in case it’s double pressed so the singlePress function knows not to do the single press action, then check and return if the last press is smaller than the press in the scope of your connection:

UIS.InputBegan:Connect(function(input, gp)
	if (input.KeyCode == Enum.KeyCode.Z) then
		local currentTime = tick()
        DRIBBLE_COMBOS.LastZPress = currentTime
		local function SinglePress()
            task.wait(DRIBBLE_COMBOS.Threshold)
            if tick() - currentTime < DRIBBLE_COMBOS.Threshold then
                return
            end
            print('Crossover')
         end
1 Like

This somewhat works, after replacing this line:

if tick() - currentTime < DRIBBLE_COMBOS.Threshold then
with
if tick() - DRIBBLE_COMBOS.LastZPress < DRIBBLE_COMBOS.Threshold then.

Now the output always says this whenever a double press occurs:

Sidestep
Crossover

(I added a print("Sidestep") before the return.)