Can someone explain to me how this double tap w to sprint script works?

Sprint Script
local UserInputService = game:GetService("UserInputService")

local player = game:GetService("Players").LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()

local sprinting = false
local lastTick = tick()
local oldWS = nil -- It doesn't work if I set the walkspeed here. Can this be explained as well?

UserInputService.InputBegan:Connect(function(input, gameProcessed)
	if gameProcessed then return end
	
	if input.KeyCode == Enum.KeyCode.W then
		local difference = tick() - lastTick
		
		if difference <= 0.8 then
			sprinting = true
			
			oldWS = character.Humanoid.WalkSpeed
			character.Humanoid.WalkSpeed = oldWS * 1.8
			print("Sprinting!")
		end
		lastTick = tick()
	end
end)

UserInputService.InputEnded:Connect(function(input, gameProcessed)
	if gameProcessed then return end
	
	if input.KeyCode == Enum.KeyCode.W and sprinting then
		sprinting = false
		
		character.Humanoid.WalkSpeed = oldWS
		print("Sprinting ended!")
	end
end)

I really don’t like using scripts I don’t understand. So an explanation of why the tick() works would be great.

I mainly want to know why the tick() part works, and that’s pretty much it. A full step-by-step explanation wouldn’t be that bad as well.

2 Likes

tick() gets the current time. So when you are trying to detect if you double tapped w, the first time you hit w you should get the time. So the next time you hit W, it has the lastTick stored so it compares it to the current time, which is the calculation of the difference. If the difference is less than 0.8 as they have, it means they are sprinting. The value 0.8 means that’s 0.8 of a second between hitting W so that’s what they define as double tapping W.

If the difference is greater than 0.8 than they just override the lastTick with the current time.

I also should say that tick()

Returns how much time has elapsed, in seconds, since the UNIX epoch, on the current local session’s computer.

5 Likes