You can write your topic however you want, but you need to answer these questions:
-
What do you want to achieve?
I want to make an NPC follow the closest player -
What is the issue?
I can´t get it to work, the pathfinding is not the issue, it is working correctly with a part in the workspace, the problem is detecting the closest player and following it -
What solutions have you tried so far? Did you look for solutions on the Developer Hub?
I tried to look for the players in the workspace instead of in the players service. I was still unable to get it to work. I tried looking for solutions in the forums but I couldn´t find anything that helped me
This is my code
local zombie = workspace.Dummy
local players = game.Players:GetChildren()
local humanoid = zombie.Humanoid
local closestPlayer = nil
local endingPoint = closestPlayer
local PFS = game:GetService("PathfindingService")
local Path = PFS:CreatePath()
local RS = game:GetService("RunService")
local distance
local closestDistance
local function GetClosestPlayer()
for i, v in pairs(game.Players:GetChildren()) do
if closestPlayer == nil then
closestPlayer = v
closestDistance = (zombie.HumanoidRootPart.Position - closestPlayer.Character.HumanoidRootPart.Position).magnitude
end
if closestPlayer then
distance = (zombie.HumanoidRootPart.Position - v.Character.HumanoidRootPart.Position).magnitude
if distance < closestDistance then
closestPlayer = v
end
end
end
end
local function ComputePath()
Path:ComputeAsync(zombie.HumanoidRootPart.Position, endingPoint.Character.HumanoidRootPart.Position)
if Path.Status == Enum.PathStatus.Success then
local Nodes = Path:GetWaypoints()
for i,v in pairs(Nodes) do
if v.Action == Enum.PathWaypointAction.Jump then
humanoid.Jump = true
end
humanoid:MoveTo(v.Position)
humanoid.MoveToFinished:Wait(1)
end
end
end
RS.Stepped:Connect(function()
GetClosestPlayer()
ComputePath()
end)