Stamina doesnt react as quick as i want

so i have this stamina system but its incredibly buggy and requires me to either jump really quickly or hold down space to get the bar to go down. can i get some tips or anything to improve this to work on jump rather than when the space bar is pressed? i also want this to work for mobile

code:

local bar = script.Parent

local stamina = 100
local staminaRate = 0.1


local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()

local humanoid = char:WaitForChild("Humanoid")


local isJumping = false


local uis = game:GetService("UserInputService")


uis.InputBegan:Connect(function(key, gameProcessed)

	if gameProcessed or stamina == 0 then return end


	if key.KeyCode == Enum.KeyCode.Space then

		isJumping = not isJumping

		if isJumping then
			humanoid.JumpPower = 50
		else
			humanoid.JumpPower = 0
		end
	end
end)

uis.InputEnded:Connect(function(key, gameProcessed)

	if gameProcessed or stamina == 0 then return end


	if key.KeyCode == Enum.KeyCode.Space then

		isJumping = not isJumping

		if isJumping then
			humanoid.JumpPower = 50
		else
			humanoid.JumpPower = 0
		end
	end
end)


while wait() do


	if stamina == 0 and isJumping then

		isJumping = false
		humanoid.JumpPower = 0
		wait(5)
	end


	if isJumping then
		stamina = stamina - 5
		wait(0.1)
	else
		stamina = stamina + 5
		wait(0.1)
	end


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

	bar:TweenSize(UDim2.new((1/100) * stamina, 0, 1 ,0), Enum.EasingDirection.InOut, Enum.EasingStyle.Quint, 0.5)
end

For improving code, go to #help-and-feedback:code-review.

can i get some tips or anything to improve this to work on jump rather than when the space bar is pressed?

There’s a lot of whitespace in your code, unless that’s just how it was pasted upon writing this post.

bar:TweenSize(UDim2.new((1/100) * stamina, 0, 1 ,0), Enum.EasingDirection.InOut, Enum.EasingStyle.Quint, 0.5)

Plus, if you’re talking about this portion of the code being slow, it would make sense because of the amount of time you’re giving.

oh i meant that if i just press the spacebar once, it wouldnt react to it at all

this is all happening in very minimal time, what is this supposed to do?

if key.KeyCode == Enum.KeyCode.Space then
		isJumping = not isJumping
		if isJumping then
			humanoid.JumpPower = 50
		else
			humanoid.JumpPower = 0
		end
	end

I bet the game processes the space bar when the player jumps. You should probably change that to not GameProcessed.

thats supposed to either allow or disallow jumping when the space bar is pressed

it’s always gonna be false though since not isJumping is false?

wait i just realized i already have something to disallow jump later in the script

but it changes isJumping to true

it does? i didn’t know that… there’s a stamina bar too right?

yea the isJumping = not isJumping is meant to make it equal the opposite of what it currently is and yea its a stamina bar