-- this script is optional and not required to have, delete it or keep it


local player = {}
local input = {}
local animation = {}

local players = game:GetService("Players")
local runservice = game:GetService("RunService")
local userinput = game:GetService("UserInputService")

do -- player
	local PLAYER = players.LocalPlayer
	
	player = setmetatable({}, {__index = function(k)
		return rawget(player, k) or PLAYER:FindFirstChild(tostring(k))
	end})
	
	local function onCharacter(character)
		wait()
		player.character = character
		player.mouse = PLAYER:GetMouse()
		player.backpack = PLAYER:WaitForChild("Backpack")
		player.humanoid = player.character:WaitForChild("Humanoid")		
		player.torso = player.character:WaitForChild("Torso")
		player.alive = true
		
		repeat wait() until player.humanoid.Parent == player.character and player.character:IsDescendantOf(game)
		animation.crouch = player.humanoid:LoadAnimation(script:WaitForChild("crouch"))
		input.stance = "stand"
		local onDied onDied = player.humanoid.Died:connect(function()
			player.alive = false
			onDied:disconnect()
			if animation.crouch then
				animation.crouch:Stop(.2)
			end
		end)
	end
	if PLAYER.Character then
		onCharacter(PLAYER.Character)
	end
	PLAYER.CharacterAdded:connect(onCharacter)
end

do -- input
	input.stance = "stand"
	local sprinting = false
	local default_right = CFrame.new(1, -1, 0, 0, 0, 1, 0, 1, 0, -1, -0, -0)
	local default_left = CFrame.new(-1, -1, 0, -0, -0, -1, 0, 1, 0, 1, 0, 0)
	runservice.RenderStepped:connect(function()
		if animation.crouch then
			if animation.crouch.IsPlaying then
				animation.crouch:AdjustSpeed(Vector3.new(player.torso.Velocity.x, 0, player.torso.Velocity.z).magnitude/10)
			end
		end
	end)
	userinput.TextBoxFocused:connect(function()
		if sprinting then
			sprinting = false
			player.humanoid.WalkSpeed = 16
		end
	end)
	userinput.InputBegan:connect(function(object, g)
		if not g then
			if object.UserInputType == Enum.UserInputType.Keyboard then
				local key = object.KeyCode
				if key == Enum.KeyCode.C then
					if input.stance == "crouch" then
						player.humanoid.HipHeight = 0
						player.humanoid.WalkSpeed = 16
						animation.crouch:Stop(.2)
						input.stance = "stand"
					else
						input.stance = "crouch"
						player.humanoid.HipHeight = -1
						player.humanoid.WalkSpeed = 16 * 0.4
						animation.crouch:Play(.2)
					end
				elseif key == Enum.KeyCode.LeftShift then
					if not sprinting then
						sprinting = true
						player.humanoid.WalkSpeed = 16 * (input.stance == "crouch" and 0.8 or 1.25)
					end
				end
			end
		end
	end)
	userinput.InputEnded:connect(function(object, g)
		if not g then
			if object.UserInputType == Enum.UserInputType.Keyboard then
				local key = object.KeyCode
				if key == Enum.KeyCode.LeftShift then
					if sprinting then
						sprinting = false
						player.humanoid.WalkSpeed = 16 * (input.stance == "crouch" and 0.4 or 1)
					end
				end
			end
		end
	end)
end
