Basically, I have a sprint script which works well but whenever I hold the LeftShift the animation starts playing when the player is standing still.
Things I tried: Detecting when player is holding the W key, detecting player velocity, detecting if the HumanoidStateType is idle (there's no idle state)
Code:
local UserInputService = game:GetService("UserInputService");
local player = game.Players.LocalPlayer or game.Players.PlayerAdded:Wait();
local PlayerGui = player:WaitForChild("PlayerGui");
local Stamina = script.Parent:WaitForChild("Stamina");
local camera = game.Workspace.Camera
local Character = player.Character
local Anim = Instance.new('Animation')
local Humanoid = player.Character:WaitForChild("Humanoid")
Anim.AnimationId = 'rbxassetid://myid'
local PlayAnim = Character.Humanoid:LoadAnimation(Anim)
local cool = false;
UserInputService.InputBegan:Connect(function(sprint)
if sprint.KeyCode == Enum.KeyCode.LeftShift then
if not cool and (not player.Character:FindFirstChild("Stun")) then
coroutine.wrap(function()
cool = true;
wait(0.85);
cool = false;
end)();
wait(0.65)
player.Backpack.Running.Value = true;
PlayAnim:Play() -- plays the running animation
return;
end;
else
return;
end;
end);
UserInputService.InputEnded:Connect(function(keyPress)
if keyPress.KeyCode == Enum.KeyCode.LeftShift then
player.Backpack.Running.Value = false;
PlayAnim:Stop() -- stops the running animation
end;
end);
local pog = false;
while wait() do
if Stamina.Value > 0 and player.Backpack.Running.Value == true or player.Character:FindFirstChild("Stun") then
local Humanoid = player.Character:WaitForChild("Humanoid");
if Humanoid.MoveDirection == Vector3.new(0, 0, 0) then
script.Parent.regenStaminaClient.Disabled = false;
else
script.Parent.regenStaminaClient.Disabled = true;
end;
Humanoid.WalkSpeed = 22; -- sprint walkspeed
local playerStats = PlayerGui:WaitForChild("playerStats");
if not pog and Humanoid.MoveDirection ~= Vector3.new(0, 0, 0) then
Stamina.Value = Stamina.Value - 1.25;
playerStats.Frame.Stamina.Bar:TweenSize(UDim2.new(Stamina.Value / 100, 0, 1, 0), Enum.EasingDirection.Out, Enum.EasingStyle.Linear, 0.1, true); -- tween stamina bar
wait(0.1);
pog = false;
end;
elseif Stamina.Value <= 0 or player.Backpack.Running.Value == false or player.Character:FindFirstChild("Stun") then
local Humanoid = player.Character:WaitForChild("Humanoid");
player.Backpack.Running.Value = false;
PlayAnim:Stop() -- stops the running anim
Humanoid.WalkSpeed = 16; -- goes back to normal walkspeed
script.Parent.regenStaminaClient.Disabled = false;
end;
end;
