Skinstashery
Roblox
Home / Roblox / Studio script library / NPC follows player
RB-004

Roblox npc follows player script

An NPC that finds the nearest player and walks to them around obstacles.

Script type
Script
Where it goes
Inside the NPC Model
Category
World and effects

For your own game in Roblox Studio. Not for use in other people's games.

The code

-- NPC that follows the nearest player using PathfindingService.
-- The model needs a Humanoid and a HumanoidRootPart.

local DETECT_RANGE = 80       -- studs; ignores players further away
local STOP_DISTANCE = 5       -- studs; stops when this close
local UPDATE_TIME = 0.4       -- seconds between path updates

local Players = game:GetService("Players")
local PathfindingService = game:GetService("PathfindingService")

local npc = script.Parent
local humanoid = npc:WaitForChild("Humanoid")
local root = npc:WaitForChild("HumanoidRootPart")

-- Let the server move the NPC smoothly (no stutter from a nearby player owning it).
pcall(function()
	root:SetNetworkOwner(nil)
end)

local function findNearestTarget()
	local nearestRoot = nil
	local nearestDistance = DETECT_RANGE

	for _, player in Players:GetPlayers() do
		local character = player.Character
		local targetHumanoid = character and character:FindFirstChildOfClass("Humanoid")
		local targetRoot = character and character:FindFirstChild("HumanoidRootPart")
		if targetHumanoid and targetRoot and targetHumanoid.Health > 0 then
			local distance = (targetRoot.Position - root.Position).Magnitude
			if distance < nearestDistance then
				nearestDistance = distance
				nearestRoot = targetRoot
			end
		end
	end

	return nearestRoot, nearestDistance
end

while humanoid.Health > 0 do
	local targetRoot, distance = findNearestTarget()

	if targetRoot and distance > STOP_DISTANCE then
		local path = PathfindingService:CreatePath({
			AgentRadius = 2,
			AgentHeight = 5,
			AgentCanJump = true,
		})

		local ok = pcall(function()
			path:ComputeAsync(root.Position, targetRoot.Position)
		end)

		if ok and path.Status == Enum.PathStatus.Success then
			local waypoints = path:GetWaypoints()
			local nextWaypoint = waypoints[2] -- waypoint 1 is where the NPC already stands
			if nextWaypoint then
				if nextWaypoint.Action == Enum.PathWaypointAction.Jump then
					humanoid.Jump = true
				end
				humanoid:MoveTo(nextWaypoint.Position)
			end
		else
			-- No path found: walk straight at the player.
			humanoid:MoveTo(targetRoot.Position)
		end
	end

	task.wait(UPDATE_TIME)
end

How to set it up

  1. Get an NPC model. In the Avatar tab, Rig Builder makes one in a click. Make sure it is not anchored.
  2. Add a Script inside the NPC model (not inside a part of it).
  3. Paste the code.
  4. Put some walls and gaps in the map and press Play. The NPC walks around them to reach you.

Change it

More in World and effects

All Roblox scripts

More Roblox tools