I've created an AI that pathfinds to the nearest player's torso, and it's producing an unwanted amount of lag considering I plan on having a large number of these AIs. I assume the problem is having to compute updated paths repeatedly due to players moving, and all AI must compute new paths every .35 seconds in my case. Anyway, here's the script:

while true do
   wait(.35)
	FindTorso()
	if found == true then
local path = game:GetService("PathfindingService"):
ComputeRawPathAsync(Pos1,Target.Position,500)
local points = path:GetPointCoordinates()	
if #points > 0 then
if #points > 1 then
	script.Parent.Nordic:MoveTo(points[2] + Vector3.new(math.random(-1.5,1.5),0,math.random(-1.5,1.5)))
else
	script.Parent.Nordic:MoveTo(points[1] + Vector3.new(math.random(-1.5,1.5),0,math.random(-1.5,1.5)))
end
end
	end
end

Here's the FindTorso function:

function FindTorso()	
found = false
if script.Parent.Nordic.Health > 0 then
Pos1 = script.Parent.Torso.Position
local Distance = 10000
Target = nil
local plrs = game.Players:GetChildren()
if #plrs > 0 then
for _,i in pairs(plrs) do
	if i.Character then
		if i.Character:FindFirstChild("Torso") then
			found = true
		local tors = i.Character.Torso
		local Apart = (Pos1 - tors.Position).magnitude
		if Apart < Distance then
			Distance = Apart
			Target = i.Character.Torso
		end
		end
		end
end
end
end	
end

2 comments

0

Yes, finding the torso usually has a lot to do with the lag. Depends on your method of finding it though.

0

Okay, I posted the FindTorso function.