--humanoid.AutoRotate = false


local root = chr:WaitForChild("HumanoidRootPart")
local torso = chr:WaitForChild("Torso")
local head = chr:WaitForChild("Head")

local rj = root:WaitForChild("RootJoint")
local rh, lh = torso:WaitForChild("Right Hip"), torso:WaitForChild("Left Hip")
local rs, ls = torso:WaitForChild("Right Shoulder"), torso:WaitForChild("Left Shoulder")
local nk = torso:WaitForChild("Neck")

rj, nk, rs, ls, rh, lh = rj:Clone(), nk:Clone(), rs:Clone(), ls:Clone(), rh:Clone(), lh:Clone()
rj.Parent, nk.Parent, rs.Parent, ls.Parent, rh.Parent, lh.Parent =
	root, torso, torso, torso, torso, torso

local rjc0, nkc0, rsc0, lsc0, rhc0, lhc0 = rj.C0, nk.C0, rs.C0, ls.C0, rh.C0, lh.C0

local transfer = script.Parent:WaitForChild("transfer")

local aiming = false
local crouch = false

local conn; conn = runService.Heartbeat:Connect(function()
	local mouseHit = mse.Hit
	
	local dist = (head.Position - cam.CFrame.p).Magnitude
	local diff = head.CFrame.Y - cam.CFrame.Y
	
	local ang = aiming and -math.rad(18) or 0
	
	nk.C0 = nk.C0:Lerp(nkc0 * CFrame.Angles(-math.atan(diff / dist), ang, 0), 0.2)
	-- repost if you hate manipulating r6 joints
	rs.C0 = rs.C0:Lerp(rsc0 * CFrame.Angles(0, 0, math.atan(diff / dist) * 0.9), 0.2)
	ls.C0 = ls.C0:Lerp(lsc0 * CFrame.Angles(0, 0, -math.atan(diff / dist) * 0.9), 0.2)
	
	--root.CFrame = CFrame.lookAt(root.Position, Vector3.new(mouseHit.X, root.Position.Y, mouseHit.Z))
	
	if crouch then
		humanoid.CameraOffset = humanoid.CameraOffset:Lerp(Vector3.new(0, -2, 0), 0.2)
		
		rj.C0 = rj.C0:Lerp(rjc0 * CFrame.new(0, 0, -1.7) * CFrame.Angles(math.rad(20), 0, 0), 0.2)
		rh.C0 = rh.C0:Lerp(rhc0 * CFrame.Angles(0, 0, -math.rad(30)) * CFrame.new(0.25, 1.7, 0), 0.2)
		lh.C0 = lh.C0:Lerp(lhc0 * CFrame.Angles(0, 0, math.rad(30)) * CFrame.new(-0.25, 1.7, 0), 0.2)
	else
		humanoid.CameraOffset = humanoid.CameraOffset:Lerp(Vector3.new(), 0.25)
		
		rj.C0 = rj.C0:Lerp(rjc0, 0.25)
		rh.C0 = rh.C0:Lerp(rhc0, 0.25)
		lh.C0 = lh.C0:Lerp(lhc0, 0.25)
	end
	
	transfer:FireServer(rj.C0, nk.C0, rs.C0, ls.C0, rh.C0, lh.C0)
	
	if humanoid:GetState() == Enum.HumanoidStateType.Dead then
		conn:Disconnect()
		return
	end
end)

UIS.InputBegan:Connect(function(inp, gp)
	if not gp then
		if inp.KeyCode == Enum.KeyCode.LeftControl and humanoid.Sit == false and humanoid.PlatformStand == false then
			crouch = true
			humanoid.WalkSpeed = 10
		end
	end
end)

UIS.InputEnded:Connect(function(inp, gp) -- i hate typing out UIS functions
	if not gp then
		if inp.KeyCode == Enum.KeyCode.LeftControl then
			crouch = false
			humanoid.WalkSpeed = 16
		end
	end
end)

script.aimEvent.Event:Connect(function(bool)
	if type(bool) == "boolean" then
		aiming = bool
	end
end)

humanoid:GetPropertyChangedSignal("Sit"):Connect(function()
	if humanoid.Sit == true then
		crouch = false
		humanoid.WalkSpeed = 16
	end
end)
