Making a sprinting/crouching system, but I can sprint and crouch at the same time

What i’m trying to make is a crouching and sprinting system. It works, but you can sprint and crouch at the same time. I don’t understand why this wouldn’t work to fix that though?

Heres the code:

-- crouch system

wait()

local uis = game:GetService("UserInputService")
local ts = game:GetService("TweenService")
local ti = TweenInfo.new(0.2, Enum.EasingStyle.Cubic, Enum.EasingDirection.Out)
local plr = game.Players.LocalPlayer
local playermodelcrouchanim = game.Players.LocalPlayer.Character.Humanoid:LoadAnimation(game.ReplicatedStorage.animations.playercrouch)
local char = plr.Character
local cam = workspace.CurrentCamera

crouching = false
sprinting = false

uis.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.LeftShift and sprinting == false then
		crouching = true
		char.Humanoid.CameraOffset = Vector3.new(0, 0.5, 0)
		char.Humanoid.WalkSpeed = 5.2
		char.Torso.LeftHip.C0 = CFrame.new(-0.5, -1.5, 0) * CFrame.Angles(math.rad(22.5), 0, 0)
		char.Torso.RightShoulder.C0 = CFrame.new(0.5, -1.5, 0) * CFrame.Angles(math.rad(22.5), 0, 0)
		playermodelcrouchanim:Play(0)
	end
	if input.KeyCode == Enum.KeyCode.LeftControl and crouching == false then
		sprinting = true
		char.Humanoid.WalkSpeed = 22.448
		ts:Create(cam, ti, {FieldOfView = cam.FieldOfView*1.125}):Play()
	end
end)

uis.InputEnded:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.LeftShift and sprinting == false then
		crouching = false
		char.Humanoid.CameraOffset = Vector3.new(0, 1, 0)
		char.Humanoid.WalkSpeed = 17.268
		char.Torso.LeftHip.C0 = CFrame.new(-0.5, -1.5, 0) * CFrame.Angles(0, 0, 0)
		char.Torso.RightShoulder.C0 = CFrame.new(0.5, -1.5, 0) * CFrame.Angles(0, 0, 0)
		playermodelcrouchanim:Stop(0)
	end
	if input.KeyCode == Enum.KeyCode.LeftControl and crouching == false then
		sprinting = false
		char.Humanoid.WalkSpeed = 17.268
		ts:Create(cam, ti, {FieldOfView = cam.FieldOfView/1.125}):Play()
	end
end)

Shouldn’t if sprinting == false then work?

2 Likes

On your InputEnded event, you should evaluate like this:
if input.KeyCode == Enum.KeyCode.LeftShift and crouching then, and
if input.KeyCode == Enum.KeyCode.LeftControl and sprinting then
This will ensure your states properly end, since the ending of the states should not be dependent on one another like the starting of each state is.

Beyond that, though, the code runs properly when I test it. I cannot replicate the problem.

Ah, I just figured out. Turns out me being an idiot caused the issue, as I forgot to delete my old sprint script before I merged the crouching and sprinting script together. :man_facepalming:

image