Run code after moving for a certain time

I am trying to make it so that after a player has moved for 3 seconds the game will give the player a coin. The problem I am having is how I am supposed to check if the player is moving and if 3 seconds have passed while moving, if the player is not moving then the timer will go to 0.

1 Like

Learn about for loops if you’re new.

1 Like

how would i use for loops for this?

1 Like

So when the event starts, you can use some debouncing + for loops I meant. Like this sorta

local db = false
-- Event
if db == false then
db = true
for i = 1, 3 do
-- Check the moving stuff
end
db = false
end

I wish I could help you more but I’m kinda busy. Good luck buddy.

Could do something like this on the server (not full code)

local Humanoid = --here
local PooledDeltaTime = 0

RunService.Heartbeat:Connect(function(DeltaTime)
local IsMoving = Humanoid.MoveDirection.Magnitude > 0.1

if IsMoving then
PooledDeltaTime += DeltaTime
else
PooledDeltaTime = 0
end

If PooledDeltaTime >= 3 then
PooledDeltaTime = 0
– Run code here
end

end)

(Wrote this on mobile sorry for unfortmattedness)

local Players = game:GetService("Players")
local RunService = game:GetService("RunService")

local local_player = Players.LocalPlayer
local character = local_player.Character or local_player.CharacterAdded:Wait()
local humanoid = character:FindFirstChildOfClass("Humanoid")

local ran_in_seconds = 0
local current_time = os.clock()

RunService.RenderStepped:Connect(function()
	if humanoid.MoveDirection.Magnitude > 0 then
		if ran_in_seconds >= 3 then
			print("ran for 3 secconds")
			ran_in_seconds = 0
			current_time = os.clock()
		else
			ran_in_seconds = os.clock() - current_time
		end
	end
end)
1 Like

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