How to make Enemy stop near the player

Im trying to have the enemy NPC stop near the player

I’ve tried to add a distance variable for the magnitude, it made the enemy go back and forth

if (torso.Position - enemy.Torso.Position).Magnitude <= 20 and (torso.Position - enemy.Torso.Position).Magnitude >= 5 then
				print("close")

this is the code

local enemy = script.Parent
local player = game.Players

function findplyr()
	for i,v in pairs(player:GetPlayers()) do
		print(v)
		if v.Character then
			local torso = v.Character.Torso
			if (torso.Position - enemy.Torso.Position).Magnitude <= 20 then
				print("close")
				enemy.Humanoid:MoveTo(torso.Position)
			else
				enemy.Humanoid:MoveTo(Vector3.new(-7.2, 3, -44.5))
				print("far")
			end
		end
	end
end


game:GetService("RunService").Heartbeat:Connect(function()
	print("running")
	findplyr()
end)

https://gyazo.com/8a5ef5fb7ab2f7337850ab42ac73272d

local enemy = script.Parent
local player = game.Players
local CurrentTarget = nil
local CurrentDist = math.huge()
local minimum = 20


function findplyr()
local Target = nil
local nearest = 100000

	for i,v in pairs(player:GetPlayers()) do
		print(v)
		if v.Character then
			local torso = v.Character.Torso
			if (torso.Position - enemy.Torso.Position).Magnitude <= nearest then
nearest = (torso.Position - enemy.Torso.Position).Magnitude
				print("close")
				Target = Torso
			
			end
		end
	end
return Target
end


game:GetService("RunService").Heartbeat:Connect(function()
	print("running")
	local torso = findplyr()

if torso then
local dist = (torso.Position - enemy.Torso.Position).Magnitude
if dist > minimum  then
enemy.Humanoid:MoveTo(torso.Position)
end
end

end)

the error was in this line:

if (torso.Position - enemy.Torso.Position).Magnitude <= 20 then
				print("close")
				enemy.Humanoid:MoveTo(torso.Position)
			else
				enemy.Humanoid:MoveTo(Vector3.new(-7.2, 3, -44.5))
				print("far")
			end

if the enemy was close to the player it would just go to the given Vector3

my script works, the npc just doesn’t stop 5 studs from the player. the gif is with the code at the top.
your script does stop the enemy but only when it isnt moving

The first script shown works, this seems like it could be caused by you never disconnecting the Heartbeat function whenever the NPC does actually meet the requirements.

Try to disconnect the Heartbeat function when it is true.

I need the enemy to check for the players though.

But you can disconnect it when It goes to the player, and just reconnect it when you want it to move again.

ok, so i think this might stop it

if (torso.Position - enemy.Torso.Position).Magnitude <= 20 then
				print("close")
				enemy.Humanoid.WalkSpeed = 0
			else
enemy.Humanoid.WalkSpeed = 16
				enemy.Humanoid:MoveTo(Vector3.new(-7.2, 3, -44.5))
				print("far")
			end

if the walk speed is set to 0 the humanoid will never move