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

How can I use PathfindingService to follow a player?

Hello dear scriptinghelpers community! I just wrote some cool Code that lets an NPC find a path to me.


		local ps = game:GetService("PathfindingService")
	local toMove = workspace:WaitForChild("Zombie Doge")
local path = ps:ComputeRawPathAsync(toMove.HumanoidRootPart.Position,workspace.Sonnenroboter.HumanoidRootPart.Position,99999999999)

-- Get the path waypoints
local waypoints = path:GetWaypoints()
for i,waypoint in pairs(waypoints) do
	toMove.Humanoid:MoveTo(waypoint.Position)
	toMove.Humanoid.MoveToFinished:Wait()
	if(waypoint.Action == Enum.PathWaypointAction.Jump)then
		print("Jump!")
		toMove.Humanoid.Jump = true
	end
	print("Done")
end

But I want that the NPC keeps going to the Player. Looping it of Course doesn't work how I want because it finishes the path and then makes a new.

How can I make it directly go to the Player?

1 answer

✓ Accepted answer

We'll have the use a loop to recompute the path it takes and use only a set number of the waypoints it provides, that number being up to you.

        local ps = game:GetService("PathfindingService")
    local toMove = workspace:WaitForChild("Zombie Doge")

local stepsUsed=1 -->=1 at least, waypoints used

while true do
	local path = ps:ComputeRawPathAsync(toMove.HumanoidRootPart.Position,workspace.Sonnenroboter.HumanoidRootPart.Position,99999999999)
	
	-- Get the path waypoints
	local waypoints = path:GetWaypoints()
	for i=1,stepsUsed do
	    local waypoint=waypoints[i]
	    if waypoint then
		    toMove.Humanoid:MoveTo(waypoint.Position)
		    toMove.Humanoid.MoveToFinished:Wait()
		    if(waypoint.Action == Enum.PathWaypointAction.Jump)then
		        print("Jump!")
		        toMove.Humanoid.Jump = true
		    end
		    print("Done")
	    end
	end
	wait()
end

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