How would I make a Npc follow the Closet Player?

local PathfindingService = game:GetService("PathfindingService")

function findNearestTorso(pos)
	local list = game.Workspace:children()
	local torso = nil
	local dist = 100000000
	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("HumanoidRootPart")
			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 true do
	wait(math.random(1,1))
	local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
	if target ~= nil then

		local path = PathfindingService:CreatePath()


		-- Get the path waypoints
		path:ComputeAsync(script.Parent.HumanoidRootPart.Position,target.Position)
		local waypoints = path:GetWaypoints()

		-- Loop through waypoints
		for _, waypoint in pairs(waypoints) do
			local part = Instance.new("Part")
			part.Shape = "Ball"
			part.Material = "Neon"
			part.Size = Vector3.new(0.6, 0.6, 0.6)
			part.Position = waypoint.Position
			part.Anchored = true
			part.CanCollide = false
			part.Parent = game.Workspace

			script.Parent.Humanoid:MoveTo(waypoint.Position)
			
		
			
			
		end

	end

end
local NPC = workspace.NPC -- Choose
local pathfinding_service = game:GetService("PathfindingService") -- Gets PathfindingService
 
function getClosestPlayer() -- Creates Function
        local closest_player, closest_distance = nil, 200 -- Makes some variables to use later
        for i, player in pairs(workspace:GetChildren()) do -- Gets everything in workspace
                if player:FindFirstChild("Humanoid") and player ~= NPC then -- Checks if is a player and is not npc
                        local distance = (NPC.PrimaryPart.Position - player.PrimaryPart.Position).Magnitude
                        if distance < closest_distance then -- Gets Closest Player From Magnitude
                                closest_player = player
                                closest_distance = distance
                        end
                end
        end
        return closest_player, closest_distance
end
 
while true do -- Loop
        local path = pathfinding_service:CreatePath() -- Creates a path, in PathfindingService
        local player, distance = getClosestPlayer() -- Calls the getClosestPlayer function
        if player and distance > 10 then 
                path:ComputeAsync(NPC.PrimaryPart.Position, player.PrimaryPart.Position) -- Asyncs the two positions
                local waypoints = path:GetWaypoints() -- Gets waypoints
                for _, waypoint in pairs(waypoints) do -- Goes over every waypoint
                        NPC.Humanoid:MoveTo(waypoint.Position) -- Makes npc walk to wayPoint
                        while true do
                                local distance = (NPC.PrimaryPart.Position - waypoint.Position).Magnitude
                                local distance_from_player = (NPC.PrimaryPart.Position - player.PrimaryPart.Position).Magnitude
                                if distance < 5 then
                                        break
                                end
                                if distance_from_player < 10 then
                                        NPC.Humanoid:MoveTo((NPC.HumanoidRootPart.CFrame*CFrame.new(0,0,-3)).p)
                                        break
                                end
                                wait()
                        end
                end
        end
        wait()
end

Use this

local PathfindingService = game:GetService("PathfindingService")

function findNearestTorso(pos)
	local list = game.Workspace:children()
	local torso = nil
	local dist = 100000000
	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("HumanoidRootPart")
			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 true do
	game:GetService("RunService").Heartbeat:Wait()
	local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
	if target ~= nil then

		local path = PathfindingService:CreatePath()

		-- Get the path waypoints
		path:ComputeAsync(script.Parent.HumanoidRootPart.Position,target.Position)
		local waypoints = path:GetWaypoints()

		-- Loop through waypoints
		for _, waypoint in pairs(waypoints) do
			local part = Instance.new("Part")
			part.Shape = "Ball"
			part.Material = "Neon"
			part.Size = Vector3.new(0.6, 0.6, 0.6)
			part.Position = waypoint.Position
			part.Anchored = true
			part.CanCollide = false
			part.Parent = game.Workspace

			script.Parent.Humanoid:MoveTo(waypoint.Position)
			script.Parent.Humanoid.MoveToFinished:Wait()
			
		end

	end
end

The wait(1) needed to go and you need a MoveToFinished

Well it does work well but if im spinning or running in a curve it doesn’t go so well

Both of the AI when they turn its a really sharp turn

How badly does it go? Could you publish it so we could see

OK I published it I will join I’m quickly getting water

The AI works then it breaks randomly

how it walks

Also for the random studdering sometimes, I recommend on the first line of the script, do this

script.Parent.PrimaryPart:SetNetworkOwner(nil)

Do you got any ideas on how to fix the sharp turns I’m going to sleep rn oof

I’m honestly unsure due to my decent lack of experience in AI, but I think it may just be Roblox’s Pathfinding? You may need to trial and error it a bit if needed

If I remove the wait() the Ai will work pefectly but the pathfinding doesn’t work

Also before you go do you know how to add wandering to This so it wanders to the closet Player?

Pathfinding wont work because it’s skipping going through all the waypoints. I think what you could do is try to find guides on how to do pathfinding like this online, there should be plenty

And for wandering, you mean like random movement?

Basically think the following script is a npc running too you and wandering is it looking for a player

so it would look for the closet player

Like the wandering would it look around for players

I think we may have to discuss this t omorrow in messages since even I’m about to go sleep lol since I’m tired, I think you may have to put one of thhe posts as the solution since your original answer has been resolved and this is a new one

1 Like