Crouch only plays when holding key instead of pressing a key

I’m having trouble with my crouch script. The crouch animation only plays when I hold down the control key, instead of pressing it once. Does anyone know what I am doing wrong?

Code
UIS.InputBegan:connect(function(key, gameProcessed)
	if key.KeyCode == Enum.KeyCode.LeftControl and gameProcessed == false then
		Humanoid.WalkSpeed = 0
		Running = false
		CAnimation:Play(0.3)
		
		
	end
end)

UIS.InputEnded:connect(function(key, gameProcessed)
	if key.KeyCode == Enum.KeyCode.LeftControl and gameProcessed == false then
		Humanoid.WalkSpeed = NormalWalkSpeed
		Running = false
		CAnimation:Stop(0.3)


	end
end)

If I read that correctly, you want the player to toggle crouch instead of hold crouch?

In that case why would you be detecting user input ended at all?

local IsCrouching = false  -- Add a debounce

UIS.InputBegan:connect(function(key, gameProcessed)
  if not gameProcessed then
	if key.KeyCode == Enum.KeyCode.LeftControl and not IsCrouching then  -- Player pressed Left Control but is not crouching
		Humanoid.WalkSpeed = 0
		Running = false
		CAnimation:Play(0.3)
	end
    if key.KeyCode == Enum.KeyCode.LeftControl and IsCrouching then  -- Player pressed left Control, and is already crouching
    -- Stop the animation here
    end
  end
end)
1 Like

I tried that before except when I press crouch a second time the animation doesn’t stop.

1 Like

Thats cause I forgot to change the debounce from false to true when the player starts crouching.

local IsCrouching = false  -- Add a debounce

UIS.InputBegan:connect(function(key, gameProcessed)
  if not gameProcessed then
	if key.KeyCode == Enum.KeyCode.LeftControl and not IsCrouching then  -- Player pressed Left Control but is not crouching
		Humanoid.WalkSpeed = 0
		Running = false
        IsCrouching = true  -- Player started crouching, set db to true
		CAnimation:Play(0.3)
    elseif key.KeyCode == Enum.KeyCode.LeftControl and IsCrouching then  -- Player pressed left Control, and is already crouching
    IsCrouching = false  -- Player stopped crouching, set db to false
    -- Stop the animation here
    end
  end
end)
2 Likes

Use :IsKeyDown(). It’s really helpful.

1 Like