-- deltarager cried here
-- 27/05/2021


repeat wait() until game:IsLoaded() and game.Workspace:FindFirstChild(game.Players.LocalPlayer.Name) ~= nil and game.Players.LocalPlayer.Character:FindFirstChild("Humanoid") ~= nil

local ReplicatedStorage	= game:GetService("ReplicatedStorage")
local UserInputService	= game:GetService("UserInputService")
local constants			= require(ReplicatedStorage["ClientModules"].Constants)

local player	= game.Players.LocalPlayer
local character	= player.Character or player.CharacterAdded:Wait()
local humanoid	= character:WaitForChild("Humanoid")
local animator	= humanoid:WaitForChild("Animator")
local oldEvent1,oldEvent2	= nil,nil
local toolEvent,toolEventDe	= nil,nil

IdleAnimation 	= animator:LoadAnimation(ReplicatedStorage.Animations.Idle)
SprintAnimation = animator:LoadAnimation(ReplicatedStorage.Animations.Sprint)
CrouchAnimation = animator:LoadAnimation(ReplicatedStorage.Animations.Crouch)

local crouching	= false
local sprinting	= false
local equipped	= false
local shooting	= false

local function Crouch()
	if sprinting then
		humanoid.WalkSpeed = 16;
		SprintAnimation:Stop()
		sprinting = false
	end
	if crouching then
		humanoid.WalkSpeed = 16
		CrouchAnimation:Stop()
	else
		if equipped then
			IdleAnimation:Play()
		end
		CrouchAnimation:Play()
		humanoid.WalkSpeed = 10
	end
	crouching	= not crouching
end

local function Sprint()
	if crouching then
		humanoid.WalkSpeed = 16
		CrouchAnimation:Stop()
		if equipped then
			IdleAnimation:Stop()
		end
		crouching = false
	end
	if sprinting then
		humanoid.WalkSpeed = 16;
		if equipped then
			SprintAnimation:Stop()
			IdleAnimation:Play()
		end
	else
		if equipped then
			IdleAnimation:Stop()
			SprintAnimation:Play()
		end
		humanoid.WalkSpeed = 24;
	end
	sprinting		= not sprinting
end


UserInputService.InputBegan:Connect(function(input,gpe)
	if gpe then return end
	if input.KeyCode == constants.sprintKey and not shooting then
		Sprint()
	elseif input.KeyCode == constants.crouchKey then
		Crouch()
	elseif input.KeyCode == Enum.KeyCode.Space then
		if crouching then
			Crouch()
		end
	end 
end)

character.ChildAdded:Connect(function(child)
	if child:IsA("Tool") then
		equipped	= true
		IdleAnimation:Play()
		if sprinting then
			IdleAnimation:Stop()
			SprintAnimation:Play()
		end
		toolEvent		= child.Activated:Connect(function()
			if child.GunType.Value ~= "heal" then
				shooting 	= true
				if sprinting then
					humanoid.WalkSpeed = 16;
					sprinting = false
					SprintAnimation:Stop()
					IdleAnimation:Play()
				end
			end
		end)
		toolEventDe	 	= child.Deactivated:Connect(function()
			shooting 	= false
		end)
	end
end)
character.ChildRemoved:Connect(function(child)
	if child:IsA("Tool") then
		equipped	= false
		IdleAnimation:Stop()
		SprintAnimation:Stop()
		
		if toolEvent ~= nil then
			toolEvent:Disconnect()
			toolEventDe:Disconnect()
		end
	end
end)


