Very inefficient boids system

they tend to just get out of the game area

local Folder = workspace:WaitForChild("Birds")
local template = workspace:WaitForChild("BirdTemplate")


local NUM_RAYS = 1000
local RAY_KEEP_ANGLE = 0.5  --1 == 0deg, 0 == 180deg, -1 = 360deg
local SIGHT_LENGTH = 25
local FOV = 0 --1 == 0deg, 0 == 180deg, -1 = 360deg

local BOID_SPEED = 50
local BOID_ROTATION_SPEED = 10

local DESIRED_KEEP_DIR = -Vector3.zAxis

local MAX_DISTANCE = 250


template.Parent = nil

local allboids : {Part} = {}

--visualze Debugging
local function VisualisePoints(points : {Vector3}, color : Color3?, t : number?)
	color = color or Color3.new(1, 1, 1)
	for i, v in points do
		local new = Instance.new("Part")
		new.Shape = Enum.PartType.Ball
		new.Anchored = true
		new.Position = v * SIGHT_LENGTH
		new.Name = i
		new.CanCollide = false
		new.CanQuery = false
		new.CanTouch = false
		new.Color = color
		new.Parent = workspace
		if t ~= nil then
			game:GetService("Debris"):AddItem(new, t)
		end
	end
	if t ~= nil then
		task.wait(t)
	end
end

--make a sphere of points in a fibonacci patern // took from https://stackoverflow.com/questions/9600801/evenly-distributing-n-points-on-a-sphere/44164075
local function fibonacci_sphere(samples)
	local points = {}
	local phi = math.pi * (math.sqrt(5.) - 1.)  --# golden angle in radians

	for i = 0, samples - 1 do
		local y = 1 - (i / (samples - 1) * 2)  --# y goes from 1 to -1
		local radius = math.sqrt(1 - y * y)  --# radius at y

		local theta = phi * i  --# golden angle increment

		local x = math.cos(theta) * radius
		local z = math.sin(theta) * radius

		table.insert(points, Vector3.new(x, y, z))
	end
	--VisualisePoints(points)
	return points
end

--remove the points that are out of the rotation angle
local function RemovePointsOutOfRange(points : {Vector3}, angle : number)
	local keep = {}
	local keepPoints = {}
	for i, point in points do
		local dotProduct = point:Dot(DESIRED_KEEP_DIR)
		if dotProduct < angle then continue end -- out of range, remove
		table.insert(keep,
			{
				dir = point,
				dist = dotProduct
			})
		table.insert(keepPoints, point)
	end
	--reorder keep so its the closest to 1 is index 1 and farthest the biggest index
	table.sort(keep, function(a, b)
		return a.dist > b.dist
	end)
	local newKeep = {}
	for i, v in keep do
		table.insert(newKeep, v.dir)
	end
	
	--VisualisePoints(keepPoints)
	return newKeep
end

--get the rays directions
local function GetRayDirections(totalTryRays : number, keepAngle : number) : {Vector3}
	return RemovePointsOutOfRange(fibonacci_sphere(totalTryRays), 1 - keepAngle)
end

-- make a new boid
local function Newboid(pos : Vector3?)
	local newboid = template:Clone()
	newboid.Position = pos
	newboid.Parent = Folder
	table.insert(allboids, newboid)
	return newboid
end

--find the unobstructed direction
local function FindUnobstructedDirection(boid : Part, rayDirs : {Vector3}) : Vector3
	local allDirs = {}
	
	local bestDir = -Vector3.zAxis
	local furthestDist = 0
	if workspace:Raycast(boid.Position, boid.CFrame.LookVector * SIGHT_LENGTH) == nil then return bestDir end
	for i, dir in rayDirs do
		local newDir = boid.CFrame:VectorToWorldSpace(dir)
		local ray = workspace:Raycast(boid.Position, newDir * SIGHT_LENGTH)
		if ray then
			if ray.Distance > furthestDist then
				bestDir = dir
				furthestDist = ray.Distance
			end
		else --ray no hit
			return dir
		end
	end
	return bestDir
end

--get the near boids in vision
local function GetNearBoids(boid : Part) : {Part}
	local nears = {}
	for i, otherBoid in allboids do
		if otherBoid == boid then continue end -- self
		
		local boidToOtherBoid = (otherBoid.Position - boid.Position).Unit
		
		local dist = (otherBoid.Position - boid.Position).Magnitude
		if dist > SIGHT_LENGTH then continue end
		
		local dotProduct = boidToOtherBoid:Dot(boid.CFrame.LookVector)
		if dotProduct < FOV then continue end
		
		--print(boid, dist, dotProduct)
		table.insert(nears,
			{
				boid = otherBoid,
				dist = dist,
				look = boidToOtherBoid,
				dotProduct = dotProduct
			})
	end
	return nears
end

--steer the boid so it avoid coliding with near boids / rule 1 of boids
local function SteerboidAwayFromNear(boid : Part, nearBoids) : Vector3
	if #nearBoids == 0 then return -Vector3.zAxis end
	local avrgLook = Vector3.zero
	for _, v in nearBoids do
		avrgLook += v.look
	end
	avrgLook = avrgLook.Unit
	return -avrgLook
end
--steer the boid so it goes in the direction of near boids / rule 2 of boids
local function SteerSameDirectionFromNearboids(boid : Part, nearBoids : {Part}) : Vector3
	if #nearBoids == 0 then return -Vector3.zAxis end
	local avarage = Vector3.zero
	for _, v in nearBoids do
		avarage += v.boid.CFrame.LookVector
	end
	return boid.CFrame:VectorToObjectSpace(avarage / #nearBoids)
end
--steer the boid to the center of near boids / rule 3 of boids
local function SteerToCenterOfNearBoids(boid : Part, nearBoids : {Part}) : Vector3
	if #nearBoids == 0 then return -Vector3.zAxis end
	local sum = Vector3.zero
	for _, v in nearBoids do
		sum += v.boid.Position
	end
	local center = sum / #nearBoids
	return -boid.CFrame:VectorToObjectSpace((boid.Position - center).Unit)
end

--make the boid go foroward
local function ForowardBoid(boid : Part, dist : number)
	boid.Position = boid.CFrame.LookVector * dist + boid.Position
end
--make the boid turn in the selected direction
local function TurnBoid(boid : Part, dir : Vector3, dt: number)
	local newDir = boid.CFrame:VectorToWorldSpace(dir).Unit
	local goalCFrame = CFrame.lookAt(boid.Position, boid.Position + newDir)
	boid.CFrame = boid.CFrame:Lerp(goalCFrame, 1 * dt * BOID_ROTATION_SPEED)
end

--update the boids
local function Updateboids(rayDirs : {Vector3}, dt : number)
	for i, boid in allboids do
		local nearBoids = GetNearBoids(boid)
		--print(boid.CFrame.LookVector)
		local dir1 = FindUnobstructedDirection(boid, rayDirs)
		local dir2 = SteerboidAwayFromNear(boid, nearBoids)
		local dir3 = SteerSameDirectionFromNearboids(boid, nearBoids)
		local dir4 = SteerToCenterOfNearBoids(boid, nearBoids)
		--print("dirs \n",dir1, "\n", dir2, "\n", dir3, "\n", dir4)
		local dir = (dir2 + dir3 + dir4).Unit
		TurnBoid(boid, dir, dt)
		TurnBoid(boid, dir1, dt)
		ForowardBoid(boid, math.min(BOID_SPEED * dt, 1))
		
		if boid.Position.Magnitude > MAX_DISTANCE then
			print(boid, "got out of the area at position", boid.Position)
			--boid:Destroy()
			table.remove(allboids, i)
		end
		
	end
end


local rayDirs = GetRayDirections(NUM_RAYS, RAY_KEEP_ANGLE)
print(rayDirs)

task.wait(1)
task.spawn(function()
	for i = 1, 100 do
		local b = Newboid(Vector3.new(math.random(-25, 25), math.random(25, 75), math.random(-25, 25)))
		b.Name = "boid" .. i
		task.wait()
	end
end)

game:GetService("RunService").Heartbeat:Connect(function(dt)
	Updateboids(rayDirs, dt)
	task.wait(1)
end)