I’m working on a sprinting script which, obviously, lets you sprint when you hold shift. However, I’m experiencing a bug wherein if the player repeatedly taps the shift key whilst their stamina is regenerating, it greatly speeds this process up. I understand why this is happening, but not how to solve it. Below is the code for this specific part of the function:
uis.InputEnded:Connect(function(input, gameProcessEvent)
if not gameProcessEvent then
if input.UserInputType == Enum.UserInputType.Keyboard then
local kc = input.KeyCode
if kc == Enum.KeyCode.LeftShift or game.Players.LocalPlayer.Character.Humanoid.MoveDirection.Magnitude <= 0 then
sprinting = false
T2:Play()
game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 5
wait(3)
while sprinting == false do
stamina.Value = stamina.Value + 2
if stamina.Value >= 100 then
break
end
wait(0.2)
end
if stamina.Value > 100 then
stamina.Value = 100
end
end
end
end
end)
The whole while sprinting == false do part of the script would likely be the culprit. You’re making the game add stamina.Value = stamina.Value + 2 multiple times over itself, thus it accelerates its own recovery. I’m trying to figure out a way to ensure that it won’t keep adding onto itself more and more if the player repeatedly taps the shift key.
Maybe have a while loop running outside of InputBegan and InputEnded, which reads sprinting and decides whether to add stamina or not:
while true do
if sprinting == false then
stamina.Value = math.clamp(stamina.Value + 2, 0, 100)
end
wait(0.2)
end
uis.InputEnded:Connect(function(input, gameProcessEvent)
if not gameProcessEvent then
if input.UserInputType == Enum.UserInputType.Keyboard then
local kc = input.KeyCode
if kc == Enum.KeyCode.LeftShift or game.Players.LocalPlayer.Character.Humanoid.MoveDirection.Magnitude <= 0 then
sprinting = false
T2:Play()
game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 5
end
end
end
end)
local regenerating = false
uis.InputEnded:Connect(function(input, gameProcessEvent)
if not gameProcessEvent then
if input.UserInputType == Enum.UserInputType.Keyboard then
local kc = input.KeyCode
if kc == Enum.KeyCode.LeftShift or game.Players.LocalPlayer.Character.Humanoid.MoveDirection.Magnitude <= 0 then
sprinting = false
T2:Play()
game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 5
wait(3)
if not regenerating then
regenerating = true
while task.wait(0.2) do
if sprinting == false then
regenerating = false
break
end
stamina.Value = stamina.Value + 2
if stamina.Value >= 100 then
regenerating = false
break
end
end
end
if stamina.Value > 100 then
stamina.Value = 100
end
end
end
end
end)