Double tap W to sprint not working?

Hi DevForum,

The title is pretty self explanatory, but I put together a script below for when you double tap W, you sprint. However, this code does not work and was wondering how to fix this. Thanks!

Script:

local player = game.Players.LocalPlayer
local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")

local normalSpeed = 16
local runSpeed = 30

local maxWTime = 0.2
local cooldown = 0

local debounce = false
local running = false

local lastTime = tick()

local UIS = game:GetService("UserInputService")


UIS.InputBegan:Connect(function(input, isTyping)
	if isTyping then return end
	
	if not debounce and not running then
		if tick() - lastTime <= maxWTime then
			
			debounce = true
			running = true
			
			humanoid.WalkSpeed = runSpeed
			
			lastTime = tick()
			
			
		end
	end
	
end)


UIS.InputEnded:Connect(function(input, isTyping)
	if isTyping then return end

	if running then
		running = false
		
		humanoid.WalkSpeed = normalSpeed
		
		wait(cooldown)
		debounce = false
	end

end)
3 Likes

You never stated what the input should be? (input.KeyCode == Enum.KeyCode.W)

✓ Possible Solution


You forgot two things:

• Detecting if W is being pressed using input.KeyCode
• Reseting timer if not below maxWTime

The new code:


Already tested this it works!

local player = game.Players.LocalPlayer
local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")

local normalSpeed = 16
local runSpeed = 30

local maxWTime = 0.2
local cooldown = 0

local debounce = false
local running = false

local lastTime = tick()

local UIS = game:GetService("UserInputService")


UIS.InputBegan:Connect(function(input, isTyping)
	if isTyping then return end
	
	if input.KeyCode == Enum.KeyCode.W then -- Detects if W is being pressed
		if not debounce and not running then

			if tick() - lastTime  <= maxWTime then -- If below the maxWTime it will act
				debounce = true
				running = true

				humanoid.WalkSpeed = runSpeed

				lastTime = tick()

				
			else  -- If not below maxWTime it will reset lastTime
				lastTime = tick()

			end
		end
	end
	

end)


UIS.InputEnded:Connect(function(input, isTyping)
	if isTyping then return end

	if running and input.KeyCode == Enum.KeyCode.W  then
		running = false

		humanoid.WalkSpeed = normalSpeed

		wait(cooldown)
		debounce = false
	end

end)
1 Like

Thanks! I made a couple silly mistakes, thanks for picking up on that!

1 Like

You’re welcome, keep up the good work!

1 Like