Crouching While Sprinting Bug

So I just added a crouching and sprinting system into my game, but the only issue is that I can crouch and sprint at the same time, and I need help to stop this from happening

local DEFAULT_SPEED = 16 -- Normal speed.
local MAXIMUM_STAMINA = 100

local STAMINA_DECREASE = 0.3
local SPRINT_KEY = Enum.KeyCode.LeftShift

local UserInputService = game:GetService("UserInputService")

local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:wait()
local Humanoid = Character:WaitForChild("Humanoid")

local Exterior = script.Parent.Parent
local Bar = script.Parent

local Sprinting = false
local StaminaAmount = MAXIMUM_STAMINA -- StaminaAmount/MAXIMUM_STAMINA

UserInputService.InputBegan:Connect(function(Key, Processed)
	if not Processed then
		if Key.KeyCode == SPRINT_KEY then
			-- Player is sprinting.

			Sprinting = true
		end
	end
end)

UserInputService.InputEnded:Connect(function(Key, Processed)
	if not Processed then
		if Key.KeyCode == SPRINT_KEY then
			-- Player stopped sprinting.

			Sprinting = false
		end
	end
end)

game["Run Service"].RenderStepped:Connect(function()
	if StaminaAmount > 0 then -- You have more than 0 stamina in your tank.
		if Sprinting then -- If you're actually holding down the key.
			if Humanoid.MoveDirection.Magnitude > 0 then
				Humanoid.WalkSpeed = SPRINT_SPEED
				StaminaAmount -= STAMINA_DECREASE
			end
		else
			Humanoid.WalkSpeed = DEFAULT_SPEED
		end
	else
		Humanoid.WalkSpeed = DEFAULT_SPEED
	end

	if StaminaAmount < MAXIMUM_STAMINA then
		-- do someting.
		Exterior.Visible = true

		local Formula = (StaminaAmount/MAXIMUM_STAMINA)
		Bar:TweenSizeAndPosition(UDim2.new(Formula, 0, 1, 0), UDim2.new(0, 1-Formula, 0, 0), Enum.EasingDirection.Out, Enum.EasingStyle.Linear, 0.1, true)

		if not Sprinting then
			StaminaAmount += 0.2
		end
	else
		-- Hide if full.

		Exterior.Visible = true
	end
end)

local Animation = script:WaitForChild("Animation")
local Track = Humanoid:LoadAnimation(Animation)
Track.Looped = true
Track.Priority = Enum.AnimationPriority.Action

local function CheckKeyDown(Key)
	if Key.KeyCode == Enum.KeyCode.C then
		Sprinting = false
		Track:Play()
		game.Players.LocalPlayer.Character.Humanoid.CameraOffset=Vector3.new(0, -1.2, 0)
		Humanoid.WalkSpeed = 9
		end
	end

local function CheckKeyUp(Key)
	if Key.KeyCode == Enum.KeyCode.C then
		Sprinting = false
		game.Players.LocalPlayer.Character.Humanoid.CameraOffset=Vector3.new(0, 0, 0)
		Track:Stop()
		Humanoid.WalkSpeed = 16
	end	
end


UserInputService.InputBegan:Connect(CheckKeyDown)
UserInputService.InputEnded:Connect(CheckKeyUp) ```

You should add a Crouching and Sprinting variable somewhere. Then, you can check if the player is crouching before making the player sprint.

2 Likes

Thanks! I already added a variable to see if the player was sprinting but I forgot to add a variable to see if the player was crouching

1 Like