-- Basic settings

local FOOTSTEP_PLACEMENT_RATE = 0.4
local GROUND_DETECTION_DISTANCE = 3.1

local plr = game.Players.LocalPlayer

game.ReplicatedStorage.Interactions.Client.Perks.ShowFootsteps.OnClientEvent:connect(function(plrs)
	
	-- Make sure character is alive
	if plr.Character ~= nil then
	
		-- Set up detection part for each player
		local ignore = plr.PlayerScripts.Functions.GetRayIgnoreList:Invoke()
		for _, i in pairs(plrs) do
			local thisChr = i.Character
			if thisChr:FindFirstChild("HumanoidRootPart") and i ~= plr then
				local left = false
				local waitTime = FOOTSTEP_PLACEMENT_RATE
				local color = Color3.fromHSV(math.random(), 1, 1)
				spawn(function()
					while wait(waitTime) do
						
						-- Check if detection part is gone or owner is gone
						if thisChr.Parent == nil or thisChr:FindFirstChild("HumanoidRootPart") == nil then
							break
						end
						
						-- Check if should place a foot step
						local ray = Ray.new(thisChr.HumanoidRootPart.Position, Vector3.new(0, -GROUND_DETECTION_DISTANCE, 0))
						local hit, hitPos = workspace:FindPartOnRayWithIgnoreList(ray, ignore, false, true)
						if hit ~= nil and thisChr.HumanoidRootPart.Velocity.Magnitude > 1 then
							
							-- Tell the owner to place a footstep
							local cfr
							if left then
								cfr = thisChr.HumanoidRootPart.CFrame * CFrame.new(-0.5, -2.95, 0)
								left = false
							else
								cfr = thisChr.HumanoidRootPart.CFrame * CFrame.new(0.5, -2.95, 0)
								left = true
							end
							plr.PlayerScripts.Functions.PlaceFootstep:Fire(cfr, color, thisChr.Humanoid)
							
							-- Set wait time to be the placement rate
							waitTime = FOOTSTEP_PLACEMENT_RATE
						
						else
							
							-- Set wait time to be quick
							waitTime = 0.033
							
						end
						
					end
				end)
			end
		end
		
	end
	
end)
