How to make a model chase a player?

Hello everyone! I am trying to fix a script to make a part chase a player, when the player is within a certain distance of the model.

The issue is the current implementation I have is too laggy, and I don’t know how to change the activate distance. Here is a video of the lag.
robloxapp-20210415-1426507.wmv (1.5 MB)
as you can see, there is an insane amount of lag, especially when the model first detects the player.

I have looked and could not find a solution. Here is the code that I am using, which is located in the model

local larm = script.Parent:FindFirstChild("Left Arm")
local rarm = script.Parent:FindFirstChild("Right Arm")

function findNearestTorso(pos)
	local list = game.Workspace:children()
	local torso = nil
	local dist = .1
	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("Torso")
			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
	return torso
end

while true do
	wait(0.1)
	local target = findNearestTorso(script.Parent.Torso.Position)
	if target ~= nil then
		script.Parent.Zombie:MoveTo(target.Position, target)
	end
end

image

I don’t even think my system is effective, does anyone know of a way to get a model, to chase a player when it is in a certain distance, that wont have the same lag?

Thank you and have a good day!

1 Like

The biggest concern I see is that it’s going through every child of the workspace to find the player’s character when :GetPlayers(), which is a function of the Players service, does exactly that, try this out?

local enemy = script.Parent
local larm = enemy:FindFirstChild("Left Arm")
local rarm = enemy:FindFirstChild("Right Arm")

--enemy.PrimaryPart:SetNetworkOwner(nil) --Uncomment if you have a primary part

function findNearestTorso(pos)
	local list = game:GetService("Players"):GetPlayers()
	local torso = nil
	local dist = 50 --Max detection distance
	local temp = nil
	for _,player in pairs(list) do
		local char = player.Character
		local rootPart = char and char:FindFirstChild("HumanoidRootPart")
		if not rootPart then continue end
		local distance = (rootPart.Position - pos).Magnitude
		if distance >= dist then continue end
		torso = rootPart
		dist = distance
	end
	return torso
end

while true do
	wait(0.1)
	local target = findNearestTorso(enemy.Torso.Position)
	if target == nil then continue end
	enemy.Zombie:MoveTo(target.Position, target)
end
3 Likes

Thank you so much! All lag is gone! (Turns out that there was also problems that caused a drop in FPS when waiting . 1 second instead of just doing wait() also this script helped alot with multi player game mode.)

2 Likes