Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do I make a enemy NPC with path finding?

This is a continuation of another post. I'm trying to make a enemy NPC that follows the nearest player using path finding. I pulled up a script from the Roblox wiki but I can't figure out how to make it follow the player and constantly update the path then follow it. Here is the script:

	local PathfindingService = game:GetService("PathfindingService")
 
-- Variables for the zombie, its humanoid, and destination
local zombie = script.Parent
local humanoid = zombie.Humanoid
local destination = game.Workspace.End
 
-- Create the path object
local path = PathfindingService:CreatePath()
 
-- Variables to store waypoints table and zombie's current waypoint
local waypoints
local currentWaypointIndex
 
local function followPath(destinationObject)
	-- Compute and check the path
	path:ComputeAsync(zombie.HumanoidRootPart.Position, destinationObject.PrimaryPart.Position)
	-- Empty waypoints table after each new path computation
	waypoints = {}
 
	if path.Status == Enum.PathStatus.Success then
		-- Get the path waypoints and start zombie walking
		waypoints = path:GetWaypoints()
		-- Move to first waypoint
		currentWaypointIndex = 1
		humanoid:MoveTo(waypoints[currentWaypointIndex].Position)
	else
		-- Error (path not found); stop humanoid
		humanoid:MoveTo(zombie.HumanoidRootPart.Position)
	end
end
 
local function onWaypointReached(reached)
	if reached and currentWaypointIndex < #waypoints then
		currentWaypointIndex = currentWaypointIndex + 1
		humanoid:MoveTo(waypoints[currentWaypointIndex].Position)
	end
end
 
local function onPathBlocked(blockedWaypointIndex)
	-- Check if the obstacle is further down the path
	if blockedWaypointIndex > currentWaypointIndex then
		-- Call function to re-compute the path
		followPath(destination)
	end
end
 
-- Connect 'Blocked' event to the 'onPathBlocked' function
path.Blocked:Connect(onPathBlocked)
 
-- Connect 'MoveToFinished' event to the 'onWaypointReached' function
humanoid.MoveToFinished:Connect(onWaypointReached)
 
followPath(destination)

1 answer

The followPath function needs a object for the parameter, then when the function is called with a object in the parameter it will attempt to move the humanoid to the object. It should be used inside a npc that has a humanoid and rootpart in it, you must call the function with a object for it to work at all.

This discussion is preserved as it was. New answers, comments, and votes are closed.