Hello, I have an issue
It’s with NPCs being moved toward a character.
The intended behavior is for the NPC to constantly move toward the character while maintaining a certain distance.
This is what I get:
It kind of rubberbands behind the player and jitters a lot.
I want it to actually move 2 studs or the threshold behind the player without the jittering
It’s not too bad but not too good either.
I don’t know if its an issue with the code or the server not replicating to the client perfectly.
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local npc = script.Parent
local humanoid = npc:WaitForChild("Humanoid")
local hrp = npc:WaitForChild("HumanoidRootPart")
-- Settings
local maxDistance = 2500
local stopDistance = 2 -- closer stop range = smoother reactions
local moveSpeed = 18 -- adjust to make it faster/slower
-- Force server physics ownership (prevents micro-lag)
hrp:SetNetworkOwner(nil)
humanoid.WalkSpeed = moveSpeed
-- Find closest alive player
local function getClosestPlayer()
local closest = nil
local shortestDistance = maxDistance
local npcPos = hrp.Position
for _, player in ipairs(Players:GetPlayers()) do
local char = player.Character
if char then
local charHRP = char:FindFirstChild("HumanoidRootPart")
local charHum = char:FindFirstChild("Humanoid")
if charHRP and charHum and charHum.Health > 0 then
local dist = (npcPos - charHRP.Position).Magnitude
if dist < shortestDistance then
shortestDistance = dist
closest = charHRP
end
end
end
end
return closest, shortestDistance
end
-- Smooth follow loop
RunService.Heartbeat:Connect(function()
if humanoid.Health <= 0 then return end
local targetHRP, distance = getClosestPlayer()
if targetHRP then
local direction = (targetHRP.Position - hrp.Position).Unit
-- Rotate smoothly toward target
local lookAt = CFrame.lookAt(hrp.Position, Vector3.new(targetHRP.Position.X, hrp.Position.Y, targetHRP.Position.Z))
hrp.CFrame = hrp.CFrame:Lerp(lookAt, 0.4)
if distance > stopDistance then
-- Ease the move speed as it gets close
local speedFactor = math.clamp((distance - stopDistance) / stopDistance, 0, 1)
humanoid:Move(direction * speedFactor, false)
else
humanoid:Move(Vector3.zero, false)
end
end
end)
Thanks