NPC Pathfinding / NPC Lagging

I have been trying to make an NPC that will pathfind to the closest player within a certain distance. The issue is the fact that everything I have attempted has failed.

I want to add a pathfinding service to this specific piece of code as it works best for my NPC:

local PositionTorso = script.Parent.Torso.Position

function findNearestTorso(pos)
	local list = game.Workspace:children()
	local torso = nil
	local dist = 100
	local temp = nil
	local human = nil
	local temp2 = nil
	for x = 1, #list do
		temp2 = list[x]
		if (temp2.className == "Model") and (temp2 ~= script.Parent) then
			temp = temp2:findFirstChild("UpperTorso")
			human = temp2:findFirstChild("Humanoid")
			if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
				if (temp.Position - pos).magnitude < dist then
					torso = temp
					dist = (temp.Position - pos).magnitude
				end
			end
		end
	end
	return torso
end

while wait(0.01) do
	local target = findNearestTorso(PositionTorso)
	if target ~= nil then
		
		
		
		script.Parent.Random.Value = false
		script.Parent.Hum:MoveTo(target.Position)
	else
		
		
		
		script.Parent.Random.Value = true
	end
	PositionTorso = script.Parent.Torso.Position
end

Problems

  1. Walks into walls as it has no pathfinding service

  2. The NPC stays behind the player at all times
    Video Of Problem 2:
    robloxapp-20230206-2059007.wmv (1.3 MB)

Can someone help me figure out a way to implement a pathfinding service into my code? I have attempted to watch tutorials and videos on how to do it but it just doesn’t work for me.

An idea I hade to fix problem 2 is to add 3-5 studs in front of me to make the NPC go to that part and not my torso.

HELP!!!

2 Likes

Pathfinding to find the nearest player isn’t the problem it’s just that pathfinding uses waypoints that are being constantly created which will result in it jittery motion or lag, I suggest making the lowest possible wait time before the path continues to ease the motion.

1 Like

pretty sure thats because ur spamming MoveTo without using wait() or movetofinished
and also use agent params and replace that while true do with game.RunService.HeartBeat

1 Like

You solved the lagging issue and I appreciate it!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.