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

My Pathfinding NPC is not following me if i move?

I have made a pathfinding NPC that works very well but I cannot get it to update the path correctly when the player it's following moves.

I have a function detecting when a player moves and think the problem might be here:

randomPlayer.Character.Humanoid.Running:connect(function()
		rawPath = pathService:ComputeRawPathAsync(script.Parent.Torso.Position, randomPlayer.Character.HumanoidRootPart.Position, 512)
		path = rawPath:GetPointCoordinates()
		
		game.Workspace.Points:ClearAllChildren()
	end)

But it does not update correctly and I can't seem to find the problem.

Here is my code:

wait(1)
while true do
	randomPlayer = game.Players:GetPlayers()[math.random(1, #game.Players:GetPlayers())]
	pathService = game:GetService("PathfindingService")
	
	wait(0.1)
		
	rawPath = pathService:ComputeRawPathAsync(script.Parent.Torso.Position, randomPlayer.Character.HumanoidRootPart.Position, 512)
	path = rawPath:GetPointCoordinates()
	
	randomPlayer.Character.Humanoid.Running:connect(function()
		rawPath = pathService:ComputeRawPathAsync(script.Parent.Torso.Position, randomPlayer.Character.HumanoidRootPart.Position, 512)
		path = rawPath:GetPointCoordinates()
		
		game.Workspace.Points:ClearAllChildren()
	end)
	
	game.Workspace.Points:ClearAllChildren()
		
	partReached = true
	
	for x = 1, #path do
			
		if partReached == true then
			partReached = false
			p = Instance.new("Part", game.Workspace.Points)
			p.CanCollide = false
			p.FormFactor = Enum.FormFactor.Symmetric
			p.Size = Vector3.new(1,1,1)
			repeat wait() until path[x] ~= nil
			p.Position = path[x]
			p.Anchored = true
			p.BrickColor = BrickColor.DarkGray()
			p.Transparency = 0
			script.Parent.MazeHumanoid:MoveTo(p.Position)
		end
			
		while partReached == false do
			wait(0.1)
			p.Touched:connect(function(part)
				if part.Parent.MazeHumanoid ~= nil or part.Parent.Parent.MazeHumanoid ~= nil then
					partReached = true
				end
			end)
		end
		
	end
end

Essentially all I need it to do is update the path it takes to the player as needed.

2 comments

0

If you have a NPC, why don't you use walktopoint?

0

It seems walktopoint is read-only

1 answer

It's as simple as this, don't make it hard on yourself:

NPC = game.Workspace.NPC
char = game.Players.LocalPlayer.Character
while true do
	NPC.Humanoid:MoveTo(char.Humanoid)
	wait(1) -- Just to make sure the script doesn't crash
end

1 comment

0

Well, I want to make the NPC find it's way through obstacles, but it seems that your script just makes it walk towards that point rather than to that point.

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