How To Make NPCs Stop Following You After A Certain Distance

How would I make it where my npc would stop following you after you are a certain distance away from it.

function findNearestTorso(pos)
	local list = game.Workspace:children()
	local torso = nil
	local dist = 1000
	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.5)
	local target = findNearestTorso(script.Parent.Torso.Position)
	if target ~= nil then
		script.Parent.Humanoid:MoveTo(target.Position, target)
	end
end

You set the limit to 1000 studs, and you made this statement:

You use an if statement to check if the distance between NPC’s torso and a player’s torso is under 1000 studs. So your problem is already solved. If the player is 1000+ studs away from the NPC, the NPC will not follow you.

1 Like