Pathfinding Service problem

Hello. I wanted to make NPC that follows someone.
But when my NPC walking he walk some laggy

Here’s video: Video
Code:

local PathfindingService = game:GetService("PathfindingService")
local Humanoid = script.Parent.Humanoid
--local Animation = Humanoid:LoadAnimation(Humanoid.Animation)
--Animation:Play()
--Animation:AdjustSpeed(1.75)

while wait() do
	for k,v in pairs(game.Players:GetPlayers()) do
		if v.Character then
			repeat wait() until v.Character.HumanoidRootPart
			repeat wait() until v.Character.Torso
			
			local mag = (script.Parent.Torso.Position-v.Character.Torso.Position).magnitude
			if mag <= 120 then
				local Path = PathfindingService:CreatePath()
				Path:ComputeAsync(script.Parent.Torso.Position,v.Character.Torso.Position)
				
				for kk,vv in pairs(Path:GetWaypoints()) do
					if vv.Action == Enum.PathWaypointAction.Jump then
						Humanoid.Jump = true
					end
					
					Humanoid:MoveTo(vv.Position)
					--Humanoid.MoveToFinished:Wait()
				end
			end
		end
	end
end

Do you know why this happens?

1 Like

My guess is because you are telling the game to calculate a new path every iteration and telling it to go to a different position all the time. You should try to avoid calculating a path whenever possible. My suggestion would be to first do a raycast from the NPC to the player and check if anything collides with the ray. This way you can figure out if you can travel in a straight line to the target. If nothing collides with the ray then just use a regular MoveTo command. If something does collide with the ray then you want to calculate a path so you can go around it. Hope this helps.

Hm… may you provide script for example if you can?

First you will have to cast a ray like this:

local Raycast = Ray.new(HumanoidRootPart.Position, PlayerHumanoidRootPart.Position - HumanoidRootPart.Position)

Once this is done we can now check if there is a part:

local Part = workspace:FindPartOnRayWithIgnoreList(Raycast, {NPC, Player.Character})
if Part then
    -- pathfind
else
    -- don't pathfind
end
2 Likes

Ok but you checked the video? I have problem with laggy movement [When he walks he lags]

Hey, this is a weird situation caused by using MoveToFinished along with constantly recalculating the path. I’d recommend using a magnitude check to wait for the npc to reach the waypoint rather than MoveToFinished. That should stop the stuttering.

1 Like