Jittery Pathfinding Script, Best Way To Fix?

I’ve taken to looking at PathfindingService again and I’ve decided to develop my own following NPC. My aim was to make it search for the closest player and then move to it. However I’ve ran into a bit of an issue. I want the script to constantly check and move to the closest player and I can’t think of a good way to implement this. I’ve taken to just calling the function repeatedly with a while wait() loop but doing this only makes movement jittery. Any help making this script run wel would be appreciated.

Code:

local PathfindingService = game:GetService("PathfindingService")
local Humanoid = script.Parent.Humanoid
local HumanoidRootPart = script.Parent.HumanoidRootPart
local MaxDistance = 200
function FindClosestTarget(MaxDist, TableOfCurrentPlayers)
	local Target
	local SmallestDistance = MaxDist
	local PlayerWithSmallerDistance
	for _, player in pairs(TableOfCurrentPlayers) do
		local distance = player:DistanceFromCharacter(HumanoidRootPart.Position)
		if distance < SmallestDistance then
			SmallestDistance = distance
			PlayerWithSmallerDistance = player
		end
	end
	Target = PlayerWithSmallerDistance
	if Target ~= nil then  --Check if it isn't nil
		print(Target.Name) 
	end
	return Target
end

function FindAndMoveToTargetPos()
	local TargetToMoveTo = FindClosestTarget(MaxDistance, game.Players:GetPlayers())
	local TargetChar = TargetToMoveTo.Character
	if TargetChar then
		local Target_HRP = TargetChar:WaitForChild("HumanoidRootPart",5)
		local path = PathfindingService:CreatePath()
		path:ComputeAsync(HumanoidRootPart.Position, Target_HRP.Position) 
		local waypoint = path:GetWaypoints()
		for i, waypoint in pairs(waypoint) do
			if waypoint.Action == Enum.PathWaypointAction.Jump then 
				Humanoid.ChangeState(Enum.HumanoidStateType.Jumping)
			end
			Humanoid:MoveTo(waypoint.Position) 
			Humanoid.MoveToFinished:Wait() 
		end
	end
	return TargetToMoveTo
end

while wait() do
	local Closest = FindClosestTarget(MaxDistance,game.Players:GetPlayers())
	local CurrentTarget = FindAndMoveToTargetPos()
	if Closest ~= CurrentTarget then
		FindAndMoveToTargetPos()
	end
end

Please tell me if I’ve formatted this wrong or something, this is my first topic.
P.S. If you want to test it and see for yourself my issue, just put the script in an unanchored R15 NPC.

1 Like

Sorry for the long wait.

There are two problems:
First, you have no check inside the FindAndMoveToTargetPos to make sure that the player, and it’s character isn’t nil.

And second, you’ll need to iterate through all of the NPC’s baseparts and set network ownership to the server. off this will fix the laggy movement of the npc.

Sidenote: you can set your loop to this and it’ll still do the same thing.

while wait() do
	FindAndMoveToTargetPos()
end
2 Likes

Thank you, I was stuck for ages on this problem