So I made a script that creates an AI with a pathfinding ability that tries to kill you. It works but the only problem is that when there are multiple people it slows down and its movement becomes stuttery. How could I fix this?
function findNearestTorso(pos)
local list = game.Workspace:children()
local torso = nil
local dist = 200
local temp = nil
local human = nil
local temp2 = nil
for x = 1, #list do
temp2 = list[x]
if (temp2.className == "Model") and (temp2 ~= script.Parent) then
temp = temp2:findFirstChild("HumanoidRootPart")
human = temp2:findFirstChild("Humanoid")
if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
if (temp.Position - pos).magnitude < dist then
torso = temp
dist = (temp.Position - pos).magnitude
end
end
end
end
if torso == nil then
else
return torso.Position
end
end
while true do
local target = findNearestTorso(script.Parent.Torso.Position)
if target ~= nil then
local pathfindingService = game:GetService("PathfindingService")
local humanoid = script.Parent.Enemy
local body = script.Parent.Torso
local path = pathfindingService:CreatePath()
path:ComputeAsync(body.Position, target)
local waypoints = path:GetWaypoints()
for k, waypoint in pairs(waypoints) do
humanoid:MoveTo(waypoint.Position)
if waypoint.Action == Enum.PathWaypointAction.Jump then
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
humanoid.MoveToFinished:Wait()
end
end
wait()
end

3 comments
This doesn't have to do with your script. Rather, it has to do with who handles the physics of the Humanoid. I'd suggest reading up on Network Ownership. (https://developer.roblox.com/en-us/articles/Network-Ownership)
You don't need to be recalculating waypoints every step. Only do it every second or so, and just save them in between. More in this article thingy: https://developer.roblox.com/en-us/articles/Pathfinding
Where would I make the script wait?