Stamina-reliant jumping does not work properly

I have a pretty simple stamina system in my game and wanted to link jumping on it.

Expected result: Stamina acts like a blocker and does not let you jump if less than N(it shouldn’t block the next jump but the current one so the value won’t go into the negatives!!)

The main problem: I have no clue how to make the script disable jumping if stamina is less than N. Matter of fact, the stamina blocking condition does not work at all on repeated jumps!

Code:

local inCooldown = false
local cooldown = 0.5
local humanoid = script.Parent:FindFirstChildOfClass("Humanoid")
local stat = game.ReplicatedStorage.PlrStats[game.Players.LocalPlayer.Name]
--Stat is a NumberValue ^


--Jump cooldown and stamina deduction.
humanoid.StateChanged:Connect(function(old,new)
	if new == Enum.HumanoidStateType.Jumping then
		humanoid:SetStateEnabled(Enum.HumanoidStateType.Jumping,false)
		stat.Stamina.Value = stat.Stamina.Value - 10
		stat.StaminaRecover.Value = false
		inCooldown = true
		task.wait(cooldown)
		stat.StaminaRecover.Value = false
		humanoid:SetStateEnabled(Enum.HumanoidStateType.Jumping,true)
		inCooldown = false
	end
end)

--the checker itself
stat.Stamina.Changed:Connect(function()
	if stat.Stamina.Value <= 10 then
		humanoid:SetStateEnabled(Enum.HumanoidStateType.Jumping,false)
	elseif stat.Stamina.Value > 10 and not inCooldown then
		humanoid:SetStateEnabled(Enum.HumanoidStateType.Jumping,true)
	end
end)
2 Likes

StateChanged is too slow for this: When the state changes, you’re already jumping

This likely isn’t the most elegant solution, but perhaps considering straight up disabling the Jumping state via SetStateEnabled. Then, detect via UserInputService when the user presses space or whatever other button they use for jumping. When you do, check if you still have enough stamina to jump. If they do, enable the jumping state and set it to true (then disable it right after).

2 Likes

This sounds…Exactly what i need.

I will try it and come back with a reply. Might be the thing.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.