Run Script not working propertly

I have a simple run script under StarterCharacterScripts. Here’s the content of it:

local speed = 22
local normalSpeed = 17
local key = Enum.KeyCode.LeftShift
local tween1, tween2 = game.TweenService:Create(game:GetService("Workspace").CurrentCamera, TweenInfo.new(0.4, Enum.EasingStyle.Sine), {FieldOfView = 70 + (speed / 4)}), game.TweenService:Create(game:GetService("Workspace").CurrentCamera, TweenInfo.new(0.4, Enum.EasingStyle.Sine), {FieldOfView = 70})
local playAnim

game:GetService("UserInputService").InputBegan:Connect(function(input, gameProcessedEvent)
	if input.KeyCode == key and not gameProcessedEvent then
       	game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = speed
		tween1:Play()
		local Anim = Instance.new("Animation")
		Anim.AnimationId = "rbxassetid://6385158800"
		playAnim = game:GetService("Players").LocalPlayer.Character:WaitForChild("Humanoid"):LoadAnimation(Anim)
		playAnim:Play()
	end
end)

game:GetService("UserInputService").InputEnded:Connect(function(input) 
	if input.KeyCode == key then
		game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = normalSpeed
		tween2:Play()
		if playAnim then
			playAnim:Stop()
		end
	end
end)

Unfortunately when you click Esc key or just click on the Roblox Esc Menu button while running, the run animation still plays after exiting the menu and your speed is still higher than the normal. Also the tween is till there. Does anybody have a good fix for that?

Thanks, Jermartynojm

The animation should end and start based on Humanoid.HumanoidStateType. There’s an event called .StateChanged and you can check if that equals Enum.HumanoidStateType. Running, RunningNoPhysics, and you can experiment with that.
Otherwise, it doesn’t make it that gamebreaking.

I had a similar problem and the solution I found was using UserInputService.KeyDown instead of what you are using. InputEnded can be a bit quirky.

Just make a for loop and check if the key is still pressed. I usually check every 0.25 sec. This method is not as efficient but at least you won’t have any problems.

Not really what I want. I use while loops as less as possible.

@Poseidon995
@myaltaccountsthis

Here’s the solution that makes the run script pefect:

You can use MenuOpened to stop the run and

--https://devforum.roblox.com/t/detect-player-idle-character/703075/3
Humanoid.Running:Connect(function(Speed)
    if Speed > 0.75 then
        -- Play walk animation
    else
        print("Player is idle")
    end
end)

to pause the animation.

Unfortunately StateChanged mostly fires running even when player is not so don’t use this.