Animation keeps looping when RunService.RenderStepped is used

Please help, Animation keeps looping when RunService.RenderStepped is used.

Okay, so I have a big bug that happens when I was just trying to make a shift to sprint system.
I have been trying to solve this bug for days but I still couldn’t solve it.

Okay so here is the script:

local rps = game.ReplicatedStorage

local movementModule = require(rps.MovementSystem)

local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local hum = char:WaitForChild("Humanoid")

local cam = workspace.CurrentCamera

local UIS = game:GetService("UserInputService")
local rs = game:GetService("RunService")
local ts = game:GetService("TweenService")

local tweenInfo = TweenInfo.new(0.5, Enum.EasingStyle.Sine, Enum.EasingDirection.Out)

local Sprinting = movementModule.Sprinting
local sprintSpeed = movementModule.SprintingValue
local walkSpeed = movementModule.DefaultWalkSpeed
local sprintFOV = movementModule.sprintFOV
local defaultFOV = movementModule.defaultFOV

local sprintAnim = script:WaitForChild("sprintAnim")
local sprintAnimTrack = hum:LoadAnimation(sprintAnim)

local FOVin = ts:Create(cam, tweenInfo, {FieldOfView = sprintFOV})
local FOVout = ts:Create(cam, tweenInfo, {FieldOfView = defaultFOV})

UIS.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.LeftShift then
		Sprinting = true
	end
end)

UIS.InputEnded:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.LeftShift then
		Sprinting = false
	end
end)

local function onSprinting()
	if hum.MoveDirection.Magnitude > 0 then
		if Sprinting == true then
			hum.WalkSpeed = sprintSpeed
			FOVin:Play()
			sprintAnimTrack:Play()
		else
			hum.WalkSpeed = walkSpeed
			FOVout:Play()
			sprintAnimTrack:Stop()
		end
	end
end

rs.RenderStepped:Connect(function()
	hum.StateChanged:Connect(function(old, new)
		if new == Enum.HumanoidStateType.Running or new == Enum.HumanoidStateType.RunningNoPhysics then
			Sprinting = true
		else
			Sprinting = false
		end
	end)
	onSprinting()
end)

Video:

  • Please try to help, help will be appreciated.

You should check first if the animation is playing already while sprinting. If not, then play.

1 Like

Thank you so much! I didn’t know about this function tbh, but thanks again!

1 Like