Having an issue stopping an animation

okay so im having an issue with stopping an animation after the player has stopped moving. This is for a crouching system in my game the problem is once the player has crouched then moved the crouch-walking animation doesnt stop, but when you let go of the crouch key it’s fine.

here is the code

local uis = game:GetService("UserInputService")

local char = script.Parent
local hum = char:WaitForChild("Humanoid")
local anim = hum:LoadAnimation(script:WaitForChild("crouched"))
local anim2 = hum:LoadAnimation(script:WaitForChild("crouchedWalk"))

local crouching = false


uis.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.C then
		
		hum.HipHeight = 2
		hum.WalkSpeed = 8
		hum.JumpPower = 0
		anim.Looped = true
		anim:Play()	
		
		hum.Running:Connect(function(speed)
			if speed > 0 then
				anim2:Play()
			elseif
				speed < 0 then
				anim2:Stop()
			end	
		end)
	end
end)

uis.InputEnded:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.C then
		
		crouching = false
		
		hum.HipHeight = 2
		hum.WalkSpeed = 16
		hum.JumpPower = 50
		anim:Stop()
		anim2:Stop()
	end
end)

this is located inside of a local script in the StarterCharacterScripts folder

I think you probably meant <=

			elseif
				speed <= 0 then
				anim2:Stop()
			end	

However since speed is a float value I recommend doing this instead, you never know if speed is equal to a small number like 0.00004 due to floating point errors with float number values which will fail the above check.

				speed <= 0.01 then
				anim2:Stop()
			end	

1 Like

tysm it took me days to fix this, have a nice day

Also one more thing to note is that you are stacking connections and creating a memory leak

if you do

		hum.Running:Connect(function(speed)
print("Running")
			if speed > 0 then
				anim2:Play()
			elseif
				speed < 0 then
				anim2:Stop()
			end	
		end)
	end

you will notice everytime you press C it will print once, then twice, then thrice.

you should move the connection outside the input began.

uis.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.C then
		
		hum.HipHeight = 2
		hum.WalkSpeed = 8
		hum.JumpPower = 0
		anim.Looped = true
		anim:Play()	
		
-		hum.Running:Connect(function(speed)
-			if speed > 0 then
-				anim2:Play()
-			elseif
-				speed < 0 then
-				anim2:Stop()
-			end	
-		end)
	end
end)
+		hum.Running:Connect(function(speed)
+			if speed > 0 then
+				anim2:Play()
+			elseif
+				speed < 0 then
+				anim2:Stop()
+			end	
+		end)
+	end