I need help with my stamina system

Hi there reader,

I’m making a stamina system and i could use some help on this issue.
I’m trying to make the walkspeed go from 30 to 8 in a fade way both when the player runs out of stamina and when the player stops running. The problem is that even if you dont have any stamina left you can just press the leftshift and release it to get 25 walkspeed for some seconds. The code is located in startercharacterscripts as a local script.

The Code:
local userInputService = game:GetService(“UserInputService”)
local replicatedStorage = game:GetService(“ReplicatedStorage”)
local players = game:GetService(“Players”)
local runService = game:GetService(“RunService”)

repeat wait() until players.LocalPlayer.Character
local character = players.LocalPlayer.Character

local maxStamina = 3000
local staminaRegen = 100
local staminaCost = 5

local sprintSpeed = 30
local walkSpeed = 8

local currentStamina = maxStamina

– Sprint Key Pressed
userInputService.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.LeftShift then
if currentStamina >= staminaCost and character.Humanoid.MoveDirection.Magnitude > 0 then
character.Humanoid.WalkSpeed = 10
wait(0.1)
character.Humanoid.WalkSpeed = 15
wait(0.25)
character.Humanoid.WalkSpeed = 25
wait(0.25)
character.Humanoid.WalkSpeed = 30
end
end
end)

– Sprint Key Released
userInputService.InputEnded:Connect(function(input)
if input.KeyCode == Enum.KeyCode.LeftShift then
character.Humanoid.WalkSpeed = 25
wait(0.05)
character.Humanoid.WalkSpeed = 20
wait(0.05)
character.Humanoid.WalkSpeed = 15
wait(0.05)
character.Humanoid.WalkSpeed = 10
wait(0.05)
character.Humanoid.WalkSpeed = 8
end
end)

runService.Heartbeat:Connect(function()
if character.Humanoid.WalkSpeed == sprintSpeed then
if currentStamina >= staminaCost and character.Humanoid.MoveDirection.Magnitude > 0 then
currentStamina = currentStamina - staminaCost
else
character.Humanoid.WalkSpeed = walkSpeed
end
else
if currentStamina < maxStamina then
wait(12)
currentStamina = 3000
elseif currentStamina > maxStamina then
currentStamina = maxStamina
end
end
end)

If you are reading this and maybe know a solution please let me know

Thanks, P0TAT0RED :grinning:

format your post’s code with three ticks like so

```
local function myfunction()
print(“this is some code”)
end
```

the result will look like this

local function myfunction()
    print(“this is some code”)
end

I think you need to re write your code to make use of the TweenService

local TweenService = game:GetService("TweenService")
userInputService.InputEnded:Connect(function(input)
    local tween = TweenService:Create(character.Humanoid, TweenInfo.new(1), {WalkSpeed = 8})
    tween:Play()
end)

This tween will slowly change walk speed over one second. It can get tricky if you have more than one tween going at a time.

Thanks so much for the reply gertkeno,

I think i got it to work the way i wanted it to with your help.
Thank you so much for the help!

1 Like