Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Can I make this AI detect and follow players faster?

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

0

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)

1

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

0

Where would I make the script wait?

1 answer

You can make it detect through character position in workspace but your code is already fastest. Sorry

This discussion is preserved as it was. New answers, comments, and votes are closed.