I am currently trying to make a sprint and stamina system. So far the stamina bar tweens, and the whole sprinting mechanic pretty much works (I have used values to define a few things, so I can easily change it later if I want to).
There is one problem with it though. If I hold sprint, but am not moving, it still reduces my stamina.
Here is the code for reference (A LocalScript located in a Frame in a Frame in a ScreenGui in StarterGui):
local player = game.Players.LocalPlayer
local character = player.Character
local UIS = game:GetService("UserInputService")
local S = game:GetService("ReplicatedStorage").StaminaSettings
local stamina = 100
local running = false
if stamina <= 0 then
character.Humanoid.WalkSpeed = 16
end
stamina = math.clamp(stamina, 0, 100)
UIS.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.LeftShift or input.KeyCode == Enum.KeyCode.RightShift then
running = true
character.Humanoid.WalkSpeed = S.SprintSpeed.Value
while stamina > 0 and running do
stamina = stamina - S.StaminaDeductionAmount.Value
script.Parent:TweenSize(UDim2.new(stamina/100, 0, 1, 0), "Out", "Linear",0)
wait()
if stamina == 0 then
character.Humanoid.WalkSpeed = 16
end
end
end
end)
UIS.InputEnded:Connect(function(input)
if input.KeyCode == Enum.KeyCode.LeftShift or input.KeyCode == Enum.KeyCode.RightShift then
running = false
character.Humanoid.WalkSpeed = 16
while stamina < 100 and not running do
stamina = stamina + S.StaminaRegenerationAmount.Value
script.Parent:TweenSize(UDim2.new(stamina/100, 0, 1, 0), "Out", "Linear",0)
wait()
if stamina == 0 then
character.Humanoid.WalkSpeed = 16
end
end
end
end)
Does anyone know the fix to my problem?