Stamina bar not working properly

Basically I have a simple sprint to run localscript located in StarterCharacterScripts which works but it allows you to keep running even if your stamina is at 0, there are no errors and the walkspeed change works when you hold and released the left shift button but you can run for an infinite amount of time.

Gif: https://gyazo.com/ed7b660afb172bf3e9d0f3e307993c5f

Code:

local Players = game:GetService("Players")

local player = Players.LocalPlayer
local UserInputService = game:GetService('UserInputService')
local Mouse = player:GetMouse()
local Character = game.Players.LocalPlayer.Character
local Humanoid = Character.Humanoid


local SprintSpeed = 25
local NormalSpeed = 16

local stamina = player.PlayerGui.Display.Frame.StaminaBar.Stamina.Value

stamina = math.clamp(stamina, 0, 100)

sprinting = false


UserInputService.InputBegan:Connect(function(input)	
	if input.KeyCode == Enum.KeyCode.LeftShift then
		sprinting = true
		player.Character.Humanoid.WalkSpeed = SprintSpeed
		--Events.Sprint:FireServer(sprinting, true)
		while stamina > 0 and sprinting do
			sprinting = true
			stamina = stamina - 0.6
			player.PlayerGui.Display.Frame.StaminaBar:TweenSize(UDim2.new(stamina / 111, 0, 0.09, 0), "Out", "Linear", 0)
			wait()
			if stamina == 0 then
				player.Character.Humanoid.WalkSpeed = NormalSpeed
			end
		end
	end
end)

UserInputService.InputEnded:Connect(function(input)	
	
	if input.KeyCode == Enum.KeyCode.LeftShift then
		sprinting = false
		player.Character.Humanoid.WalkSpeed = NormalSpeed
		--Events.Sprint:FireServer(sprinting, false)
		while stamina < 100 and not sprinting do
			stamina = stamina + 0.2
			player.PlayerGui.Display.Frame.StaminaBar:TweenSize(UDim2.new(stamina / 111, 0, 0.09, 0), "Out", "Linear", 0)
			wait()
			if stamina == 0 then
				player.Character.Humanoid.WalkSpeed = NormalSpeed
			end
			
			
		
		end
	end
end)

Instead of using the method you’re using, try using :IsKeyDown. So when the player clicks a button, you check if it’s the left shift key, and then from there you loop and check WHILE left shift key is down, sprint.

More information here:
https://developer.roblox.com/en-us/api-reference/function/UserInputService/IsKeyDown

1 Like