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)
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)
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
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.