How to reset a timer?

  1. What do you want to achieve?
    I want the timer to reset back to 0 when the player moves, but also when the player is idle, it counts to 10 then resets to 0.

  2. What is the issue?
    Whenever I move, the initial timer still continues.

This is my code:

local plr = game.Players.LocalPlayer
local char = plr.CharacterAdded:wait()
local hum = char:WaitForChild("Humanoid")
local rootpart = char:WaitForChild("HumanoidRootPart")
local timeHitGround = os.time()

function isOnGround(s)
	local state = s or hum:GetState()
	return (state == Enum.HumanoidStateType.Running or state == Enum.HumanoidStateType.RunningNoPhysics or state == Enum.HumanoidStateType.StrafingNoPhysics or hum.FloorMaterial ~= Enum.Material.Air)
end

local state = hum:GetState()
local onGround = isOnGround(state) 

while task.wait() do
	timeHitGround = onGround and timeHitGround or os.time()
if rootpart.Velocity.Magnitude < .5 then
	timeOnGround = (math.floor(os.time()- timeHitGround)) % 10
else
	timeOnGround = 0
end
	print(timeOnGround)
end

Video demostration:

I am still a fairly new scripter trying to learn, any help would be appreciated! :slight_smile:

1 Like

replace this with
timeOnGround = os.time()

image

Yeah I tried that and it gave me this weird number, the initial numbers are still counting though.

You’re not updating the onGround variable inside your while loop. This means that onGround is only set once at the start of the script and never updated again meaningtimeHitGround is not being reset when the player moves.

Try this and let me know if it workss,

local plr = game.Players.LocalPlayer
local char = plr.CharacterAdded:wait()
local hum = char:WaitForChild("Humanoid")
local rootpart = char:WaitForChild("HumanoidRootPart")
local timeHitGround = os.time()

function isOnGround(s)
	local state = s or hum:GetState()
	return (state == Enum.HumanoidStateType.Running or state == Enum.HumanoidStateType.RunningNoPhysics or state == Enum.HumanoidStateType.StrafingNoPhysics or hum.FloorMaterial ~= Enum.Material.Air)
end

while task.wait() do
	local onGround = isOnGround() 
	if onGround then
		if rootpart.Velocity.Magnitude < .5 then
			timeOnGround = (math.floor(os.time()- timeHitGround)) % 10
		else
			timeOnGround = 0
			timeHitGround = os.time()
		end
	else
		timeHitGround = os.time()
	end
	print(timeOnGround)
end
1 Like

Yup, it works! Thanks a lot! I’ll have an in-depth look in this and learn from it! :slight_smile:

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