Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

You can still sprint when stamina < 0. What have I missed?

I'm not too sure what I have missed, but there is something as you can still Sprint when Stamina has fallen into the Negatives.

local mouse = game.Players.LocalPlayer:GetMouse()
local player = game.Players.LocalPlayer
running = false

local function onKeyDown( key )
    print("Key:", key, " Code:", string.byte(key))
	if string.byte(key) == 48 and script.Parent.Stamina.Value > 0 and running == false then
		hum = player.Character.Humanoid
		hum.WalkSpeed = 25
		script.Parent.Stamina.Value = script.Parent.Stamina.Value - 1
		script.Parent.Size = script.Parent.Size - UDim2.new(0,2,0,0)
		
		
		
		running = true
	while running == true do
		script.Parent.Stamina.Value = script.Parent.Stamina.Value - 5
		script.Parent.Size = script.Parent.Size - UDim2.new(0,2,0,0)
		
		wait(0.1)
		
		end
	
	else 
		
		hum = player.Character.Humanoid
		
		
		hum.WalkSpeed = 16	
		
		running = false
	end





end
mouse.KeyDown:connect(onKeyDown)

1 answer

✓ Accepted answer

You check once, that if statement will never run again. Ever. Running will be true 100% of the time.

Running is set to false in the else statement you will never reach.

This works, i have tested it. It will also only sprint if you HOLD shift.

local mouse = game.Players.LocalPlayer:GetMouse()
local player = game.Players.LocalPlayer
local up = false

local function onKeyDown( key )
	print("Key:", key, " Code:", string.byte(key))
	if string.byte(key) == 48 then
		up = false
		hum = player.Character.Humanoid
		hum.WalkSpeed = 25
		script.Parent.Stamina.Value = (script.Parent.Stamina.Value ~= 0) and script.Parent.Stamina.Value - 1 or 0 -- This causes it to only take your stamina if you have greater than 0. So it does not go negative.
		script.Parent.Size = script.Parent.Size - UDim2.new(0,2,0,0)
		while (script.Parent.Stamina.Value > 0) and not (up) do -- Only loops if Stamina is greater than 0 AND you are holding shift.
			script.Parent.Stamina.Value = script.Parent.Stamina.Value - 5
			script.Parent.Size = script.Parent.Size - UDim2.new(0,2,0,0)
			wait(0.1)
		end
		hum.WalkSpeed = 16  -- When the loop ends(release key/run out of stamina) it will reset it
	end
end

mouse.KeyDown:connect(onKeyDown)
mouse.KeyUp:connect(function(key) -- Anonymous function, you need to know when the key is released so it only works when you HOLD it.
	if string.byte(key) == 48 then
		up = true
	end
end)

3 comments

0

Edit: uncommented the lines for your gui size. I did not use a gui for testing so i commented them out.

0

Heh, thanks for pointing that out.

0

No problem.

This discussion is preserved as it was. New answers, comments, and votes are closed.