Spamming shift goes over the max amount

Why does spamming the shift button make the bar go over the max amount its set at?

local userInput = game:getService('UserInputService')
local Players = game:GetService('Players')

local walkSpeed = 16

local ManaChargeTime = 0.5
local player = Players.LocalPlayer
local Class = player:WaitForChild("Stats").Class
local Mana = player:WaitForChild("Stats").Mana
local maxMana = player:WaitForChild("Stats").MaxMana
local running = false
local isWalking

local function beginSprint(input, gameProcessed)
	player.Character.Humanoid.Running:connect(function(speed)
		if speed > 0 then isWalking = true
		elseif speed < 1 then
			isWalking = false
		end
	end)
	if Class.Value == "Light" then
		if not gameProcessed then
			if input.UserInputType == Enum.UserInputType.Keyboard then
				local keycode = input.KeyCode
				if keycode == Enum.KeyCode.LeftShift then
					if Mana.Value >= 1 and isWalking == true then
						local sprintSpeed = player:WaitForChild("Stats").SpeedValue.Value
						running = true
						player.Character.Humanoid.WalkSpeed = sprintSpeed
						while Mana.Value > 0 and running do
							if isWalking == false then
								player.Character.Humanoid.WalkSpeed = walkSpeed
								task.wait(ManaChargeTime)
								Mana.Value = Mana.Value + 1
							elseif isWalking == true then
								local sprintSpeed = player:WaitForChild("Stats").SpeedValue.Value
								player.Character.Humanoid.WalkSpeed = sprintSpeed
								task.wait(0.2)
								Mana.Value = Mana.Value - 1
								if Mana.Value == 0 then
									player.Character.Humanoid.WalkSpeed = walkSpeed
								end
							end
						end
					end
				end
			end
		end
	end
end

local function endSprint(input, gameProcessed)
	if Class.Value == "Light" then
		if not gameProcessed then
			if input.UserInputType == Enum.UserInputType.Keyboard then
				local keycode = input.KeyCode
				if keycode == Enum.KeyCode.LeftShift then
					local sprintSpeed = player:WaitForChild("Stats").SpeedValue.Value
					running = false
					player.Character.Humanoid.WalkSpeed = walkSpeed
					while Mana.Value < maxMana.Value and not running do
						task.wait(ManaChargeTime)
						Mana.Value = Mana.Value + 1
						if Mana.Value == 0 then
							player.Character.Humanoid.WalkSpeed = walkSpeed
						end
					end
				end
			end
		end
	end
end

userInput.InputBegan:Connect(beginSprint)
userInput.InputEnded:Connect(endSprint)

image

Because you

  1. Check if you’re below the max
  2. Wait a bit
  3. Increase mana

When you spam keypresses, between steps (1) and (3) on the first keyup event, a second keyup event has also done their own check before the mana changed.

So what’s happening is:

The easy solution is to double check after your task.wait

You have the same problem with the keydown method, by the way. I bet you’d be able to decrease below 0 if you tried.

What would I have to add to double check?

You’d need to repeat the condition in your while loop, because conditions may have changed since you last checked:

while Mana.Value < maxMana.Value and not running do
  task.wait(ManaChargeTime)

  -- double check:
  if Mana.Value < maxMana.Value and not running then
    Mana.Value = Mana.Value + 1
    if Mana.Value == 0 then
      player.Character.Humanoid.WalkSpeed = walkSpeed
    end
  end
end

Although since you don’t actually do anything before the wait, you could just wait before you check the condition:

while task.wait(ManaChargeTime) and Mana.Value < maxMana.Value and not running do
  Mana.Value = Mana.Value + 1
  if Mana.Value == 0 then
    player.Character.Humanoid.WalkSpeed = walkSpeed
  end
end

I don’t know where to put it and I tried too but it wasn’t working sorry to bother you can you help moi out :)?

Add a debounce so the player can only use the shift key every fraction of a second or so.

This is your code with the modifications.

You still have other bugs, but this particular one is solved.

local userInput = game:getService('UserInputService')
local Players = game:GetService('Players')

local walkSpeed = 16

local ManaChargeTime = 0.5
local player = Players.LocalPlayer
local Class = player:WaitForChild("Stats").Class
local Mana = player:WaitForChild("Stats").Mana
local maxMana = player:WaitForChild("Stats").MaxMana
local running = false
local isWalking

local function beginSprint(input, gameProcessed)
	player.Character.Humanoid.Running:connect(function(speed)
		if speed > 0 then isWalking = true
		elseif speed < 1 then
			isWalking = false
		end
	end)
	if Class.Value == "Light" then
		if not gameProcessed then
			if input.UserInputType == Enum.UserInputType.Keyboard then
				local keycode = input.KeyCode
				if keycode == Enum.KeyCode.LeftShift then
					if Mana.Value >= 1 and isWalking == true then
						local sprintSpeed = player:WaitForChild("Stats").SpeedValue.Value
						running = true
						player.Character.Humanoid.WalkSpeed = sprintSpeed
						while Mana.Value > 0 and running do
							if isWalking == false then
								player.Character.Humanoid.WalkSpeed = walkSpeed
								task.wait(ManaChargeTime)
								if Mana.Value > 0 and running then
									Mana.Value = Mana.Value + 1
								end
							elseif isWalking == true then
								local sprintSpeed = player:WaitForChild("Stats").SpeedValue.Value
								player.Character.Humanoid.WalkSpeed = sprintSpeed
								task.wait(0.2)
								if Mana.Value > 0 and running then
									Mana.Value = Mana.Value - 1
									if Mana.Value == 0 then
										player.Character.Humanoid.WalkSpeed = walkSpeed
									end
								end
							end
						end
					end
				end
			end
		end
	end
end

local function endSprint(input, gameProcessed)
	if Class.Value == "Light" then
		if not gameProcessed then
			if input.UserInputType == Enum.UserInputType.Keyboard then
				local keycode = input.KeyCode
				if keycode == Enum.KeyCode.LeftShift then
					local sprintSpeed = player:WaitForChild("Stats").SpeedValue.Value
					running = false
					player.Character.Humanoid.WalkSpeed = walkSpeed
					while task.wait(ManaChargeTime) and Mana.Value < maxMana.Value and not running do
						Mana.Value = Mana.Value + 1
						if Mana.Value == 0 then
							player.Character.Humanoid.WalkSpeed = walkSpeed
						end
					end
				end
			end
		end
	end
end

userInput.InputBegan:Connect(beginSprint)
userInput.InputEnded:Connect(endSprint)

I would also suggest a redesign of this code. Things get a little uncertain when you add waits to event handlers.

I would maybe have a single loop, outside of any event handlers, that just figures out how much mana should change on a given frame, and sets the character state accordingly.

It works but for some reason when I press spam shift it regens mana on the bar very fast

Yes, that would be because you should make the changes I suggested.

Right now, when you spam shift, this happens:

Basically the waits are overlapping so multiple increases/decreases happen in quick succession. If you like I can give you an example of the refactor.

That would be appreciated. as i used the script you gave me.

The script I gave you just answered the specific question you asked.

Here is a fairly complete rewrite, for learning purposes.

The main idea is to do a lot less inside the event handlers.

Then you just update your state every single frame (see the last four lines).

I added another mana draining effect when you hold “E”, so you can see how you might be able to extend this to do more stuff.

Hopefully it’s commented well enough, but please let me know if you have questions!

local SPRINT_COST = 5	-- mana per second cost to sprint
local CAST_COST = 10	-- mana per second cost to cast a spell

local MANA_REGEN = 5 -- mana per second regen, if nothing is draining it

local WALK_SPEED = 16

local userInput = game:getService('UserInputService')
local players = game:GetService('Players')
local run = game:GetService("RunService")

local player = players.LocalPlayer
local stats = player:WaitForChild("Stats")

local class = stats.Class
local mana = stats.Mana
local maxMana = stats.MaxMana
local sprintSpeed = stats.SpeedValue

-- We keep track of some basic character state here:
local isWalking = false
local isSprinting = false
local isCasting = false

-- Input methods just set some of those bools and nothing else
local function HandleInput(input, gp, began)
	if gp then return end
	if input.UserInputType == Enum.UserInputType.Keyboard then
		local key = input.KeyCode
		if key == Enum.KeyCode.LeftShift then
			isSprinting = began -- true on keydown, false on keyup
		elseif key == Enum.KeyCode.E then
			print("down")
			isCasting = began
		end 
	end
end
userInput.InputBegan:Connect(function(input, gp) HandleInput(input, gp, true) end)
userInput.InputEnded:Connect(function(input, gp) HandleInput(input, gp, false) end)

-- You might need something other than player.Character if this script is somewhere
-- other than StarterCharacterScripts. For example, you might need to use
-- player.CharacterAdded:Connect(function(char) char.Humanoid.Running....
player.Character.Humanoid.Running:Connect(function(speed)
	isWalking = speed > 0
end)


-- Figures out how much mana should change this frame
local function UpdateMana(frameDuration)
	local mps = 0 -- mana per second, which we calculate...
	
	-- 1. Apply cost of isSprinting, if any
	if isSprinting then
		mps = mps - SPRINT_COST
	end
	
	-- 2. Apply cost of other effects (casting a spell, for example)
	if isCasting then
		mps = mps - CAST_COST
	end
	
	-- 3. If we aren't draining mana from anything we want to increase it
	if mps >= 0 then
		mps = MANA_REGEN
	end
	
	-- 4. Figure out what the new mana value this frame could be
	local newMana = mana.Value + mps * frameDuration -- the * frameDuration is the "per second" part
	
	-- 5. Keep it within the [0, maxMana] range
	if newMana < 0 then newMana = 0 end
	if newMana > maxMana.Value then newMana = maxMana.Value end
	
	mana.Value = newMana
end

-- Figures out what the character's walkspeed should be
local function UpdateCharacterState()
	-- set isSprinting to false if we're out of mana or aren't walking
	if not isWalking or mana.Value <= 0 then
		isSprinting = false
	end
	
	if mana.Value <= 0 then
		isCasting = false
	end
	
	-- might need more checks here (does character exist, etc.)
	local humanoid = player.Character.Humanoid
	
	if isSprinting then
		humanoid.WalkSpeed = sprintSpeed.Value
	else
		humanoid.WalkSpeed = WALK_SPEED
	end
	
	if isCasting then
		player.Character.Head.Size = Vector3.new(2, 2, 2)
	else
		player.Character.Head.Size = player.Character.Head.OriginalSize.Value
	end
end

-- Update the character state and mana every physics frame
run.Heartbeat:Connect(function(dt)
	UpdateCharacterState()
	UpdateMana(dt)
end)

The UpdateMana function shows how multiple draining effects can stack.

  • If you’re sprinting, you’ll lose 5 mana/sec.
  • If you’re also casting, you’ll lose 15 mana/sec.
  • If you stop sprinting, you’ll lose 10 mana/sec.
  • If you’re doing neither, you’ll gain 5 mana/sec.

The UpdateCharacterState function shows how we do a few simple checks and then update what the physical character is doing.

This pattern (using events to set boolean variables, and then using a loop to check them) is really useful in a lot of situations!

I get an error saying
PlayerScripts.LocalScript:44: attempt to index nil with ‘Humanoid’

You’ll note the comment above that function that explains the issue and a possible solution :slight_smile:

You might also want to use WaitForChild on the humanoid

player.CharacterAdded:Connect(function(char)
	local humanoid = char:WaitForChild("Humanoid").Running:Connect(function(speed)
		isWalking = speed > 0
	end)
end)