How would i write the crouch script?

Hello Everyone!

today i mate asked me to make a crouch system

but im a bit lost how would i make the section where it lets you un crouch

i tried using true and false Boolean using a remote event with a argument that uses the Boolean
but i just wont work :frowning:

tbh this code is badly made…

i wanna see if anyone can help me with the system.

Thanks alot!

local RS = game:GetService("ReplicatedStorage")

RS.Crouch.OnServerEvent:Connect(function(player, state)
	player:SetAttribute("Crouching", state)

	local char = player.Character
	if not char then return end

	local hum = char:FindFirstChild("Humanoid")
	if not hum then return end

	local anim = hum:FindFirstChild("CrouchAnimTrack")
	if not anim then
		anim = hum:LoadAnimation(script.CrouchAnime)
		anim.Name = "CrouchAnimTrack"
		anim.Parent = hum
	end

	if state == true then
		anim:Play()
	else
		anim:Stop()
	end
end)
2 Likes

Add a print statement at the if state part below else, see if that runs. Are there any errors

First off, you should handle this entirely on the client-side to minimize input lag. (I’ve played games with server-sided crouching and it’s extremely frustrating. And client animations replicate to the server)

As for the issues, how does the client script work? Does it fire the proper remote and use proper arguments?

1 Like

As @Minerdude_alt said, you need to handle it on client like in StarterCharacterScripts or something.

I have this rough example of a crouch script from my past games which has the thing you are looking for:

--// Configuration
local keybind = "C"
local animationId = 13394734289--> Replace the number with your animation ID!
  

--// Variables
local UserInputService = game:GetService("UserInputService")

local player = game:GetService("Players").LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")

local animation = Instance.new("Animation")
animation.AnimationId = 'rbxassetid://' .. animationId

local animationTrack = humanoid:WaitForChild("Animator"):LoadAnimation(animation)
animationTrack.Priority = Enum.AnimationPriority.Action

local crouching = false


--// Functions
UserInputService.InputBegan:Connect(function(input, gameProcessedEvent)
	if gameProcessedEvent then return end

	if input.KeyCode == Enum.KeyCode[keybind] then
		if crouching then
			humanoid.WalkSpeed = 16
			crouching = false
			animationTrack:Stop()
			character.HumanoidRootPart.CanCollide =  true
		else
			humanoid.WalkSpeed = humanoid.WalkSpeed/2
			crouching = true
			animationTrack:Play()
			character.HumanoidRootPart.CanCollide =  false
		end
	end
end)

Just use InputBegan thing to call the function, that’s the whole magic! Hope this helps! :hidere: