Function When player stands still past time limit

I am trying to make a script that fires a function when the player stands still for more then 60 secs. How would I do that?

local players = game:GetService("Players")
local timer = 0
local afk = false

game.Players.PlayerAdded:Connect(function(Player)
	local char = Player.Character
	local hum = char.Humanoid
	while true do wait(1)
		timer += 1
		print(timer)
		hum.Running:Connect(function(speed)
			if speed >= 1 then
				print("Timer Reset")
				timer = 0
			end
		end)
	end
end)```

I’ve had weird scenarios where Running would fire even if the player wasn’t moving. I think utilizing the humanoid’s MoveDirection property would give you a more consistent result.

local AFK_TIME = 60 --//Player goes AFK after this amount of time elapses

local isAFK = false
local timeStandingStill = 0

local charModel --//Path to some character

local function isPlayerStandingStill()
local moveDirection = charModel.Humanoid.MoveDirection

return moveDirection == Vector3.new()
end

game:GetService("RunService").Heartbeat:Connect(function(dt)
if isPlayerStandingStill() then
timeStandingStill += dt --//Add dt to the total time elapsed of the player standing still

if timeStandingStill >= AFK_TIME then
--//Player is now AFK
isAFK = true
end
else
--//Player is active
timeStandingStill = 0
isAFK = false
end
end)

Sorry for bad formatting. It’s annoying how Roblox still hasn’t added more tools for making posts on here.

1 Like
local players = game:GetService("Players")
local run = game:GetService("RunService")

players.PlayerAdded:Connect(function(player)
	local connection, startTime, endTime
	player.CharacterAdded:Connect(function(character)
		local humanoid = character:WaitForChild("Humanoid")
		humanoid:GetPropertyChangedSignal("MoveDirection"):Connect(function()
			startTime, endTime = tick(), tick()

			if connection then
				connection:Disconnect()
				connection = nil
			end
			
			connection = run.Stepped:Connect(function(elapsed, delta)
				endTime += delta
				if endTime - startTime > 60 then
					connection:Disconnect()
					print("AFK for 60 seconds!")
					--Do code here.
				end
			end)
		end)
	end)
end)