Start building

Roblox Chasing NPC Script (Smart PathfindingService)

Finds the nearest player within detection range and computes obstacle-avoiding paths using PathfindingService.

Type: ScriptExplorer: Inside your NPC Rig ModelLevel: Intermediate
ScriptInside your NPC Rig Model
-- Script inside an NPC Rig Model
local Players = game:GetService("Players")
local PathfindingService = game:GetService("PathfindingService")

local npc = script.Parent :: Model
local humanoid = npc:WaitForChild("Humanoid") :: Humanoid
local root = npc:WaitForChild("HumanoidRootPart") :: BasePart
local DETECT_RANGE = 60

local function nearestTarget(): BasePart?
	local best: BasePart? = nil
	local bestDist = DETECT_RANGE
	for _, p in ipairs(Players:GetPlayers()) do
		local tr = p.Character and p.Character:FindFirstChild("HumanoidRootPart") :: BasePart?
		local th = p.Character and p.Character:FindFirstChildOfClass("Humanoid")
		if tr and th and th.Health > 0 then
			local d = (tr.Position - root.Position).Magnitude
			if d < bestDist then bestDist = d; best = tr end
		end
	end
	return best
end

task.spawn(function()
	while humanoid.Health > 0 do
		local target = nearestTarget()
		if target then
			local path = PathfindingService:CreatePath({ AgentCanJump = true })
			path:ComputeAsync(root.Position, target.Position)
			if path.Status == Enum.PathStatus.Success then
				local waypoints = path:GetWaypoints()
				if waypoints[2] then
					if waypoints[2].Action == Enum.PathWaypointAction.Jump then humanoid.Jump = true end
					humanoid:MoveTo(waypoints[2].Position)
				end
			end
		end
		task.wait(0.25)
	end
end)

How to install in Studio

  1. Insert an R15 Rig in Workspace (make sure HumanoidRootPart is NOT anchored).
  2. Insert a Script inside the NPC Model and paste the code.
  3. Press Play and walk within 60 studs to watch the NPC navigate around obstacles toward you.

Tips & customization

  • Call `root:SetNetworkOwner(nil)` at the top so the server owns the NPC smoothly without stuttering when players pass by.

Common questions.

Why isn't my Roblox NPC moving?

Check that none of the NPC's parts (especially HumanoidRootPart) have Anchored = true.

More free Luau scripts.

All 16 scripts

Skip manual wiring.
Let Revix code & playtest it.

Start building free

Free to start. No card needed.