How do I fix humanoid running property "stuttering"?

Not sure if I phrased the title the best, so please feel free to ask for clarification if you need it.
My script is server side and is inside of pathfinding script inside of an npc. But for whatever reason my animation gets all buggy, I’m guessing it’s something with the humanoid running property, but to be honest I’m a bit lost.
Script

npc = script.Parent.Parent
hum = script.Parent.Parent:WaitForChild('Humanoid')
runA = Instance.new("Animation")
runA.AnimationId = 'rbxassetid://11949111737'
run = hum.Animator:LoadAnimation(runA)
run.Looped = true
local function whenMoving()
	run:Play()
	print("moving")
end

local function whenNotMoving()
	run:Stop()
	print("not moving")
end
npc:WaitForChild("Humanoid").Running:Connect(function(status) 
	if status > 1 then
		whenMoving() 
	else
		whenNotMoving() 
	end
end) 

script.Parent.Parent:WaitForChild("Humanoid").Died:Connect(function()
	print("death detected")
	wait(2)
	script.Parent.Parent:Destroy()
end)

What it is outputting
image_2022-12-28_232145557

1 Like

I think you are firing whenMoving() function (the one playing the animation) lot of times, when this event happens:

npc:WaitForChild("Humanoid").Running:Connect(function(status) 
	if status > 1 then
		whenMoving() 
	else
		whenNotMoving() 
	end
end)

It will fire many times, replaying your run:Play() animation

Add a lock/debouce maybe would fix it:

local MovingNow = false
npc:WaitForChild("Humanoid").Running:Connect(function(status) 
	if status > 1 then
		if not MovingNow then
			MovingNow = true
			whenMoving()
		end
	else
		if MovingNow then
			MovingNow = false
			whenNotMoving() 
		end
	end
end)
1 Like

moving
not moving
moving

Any ideas? I’m not sure if I’m just doing something stupid or if it’s something else.

The reason the animation was “stuttering” was because I was using a looped animation. But if you remove the looped property, and just use a normal animation, it will work a lot better.
(You can also use a looped animation for the walk cycle, since it will only play once, so it shouldn’t be a problem.)