Today i started on a simple horror game project, and i had to figure out how to use path finding service for it. I looked over the devhub and i got a pretty basic grasp of it. I ended up making one of my test dummies follow the nearest player but its a little bit janky and not to my liking
Heres the code
local NPC = script.Parent
local Players = game.Players
local PFS = game:GetService("PathfindingService")
local function MoveToClosestPlayer()
local npcHum = NPC.Humanoid
local npcHRP = NPC.HumanoidRootPart
local closestDistance = math.huge
for i, player in pairs(Players:GetPlayers()) do
print(player,"is player", i)
local char = player.Character or player.CharacterAdded:Wait()
if char then
local HRP = char.HumanoidRootPart
if HRP then
local distance1 = (npcHRP.Position - HRP.Position).Magnitude
if distance1 < closestDistance then
print(distance1)
local closestHRP = HRP
print(closestHRP.Position)
local destination = closestHRP.Position
local path = PFS:CreatePath()
path:ComputeAsync(npcHRP.Position, destination)
local waypoints = path:GetWaypoints()
for _, v in pairs(waypoints) do
npcHum:MoveTo(v.Position)
if v.Action == Enum.PathWaypointAction.Jump then
npcHum.Jump = true
end
end
end
end
end
end
end
while task.wait() do
MoveToClosestPlayer()
end
I believe i know where the issue is lying. The while wait is constantly running the function creating multiple paths and the dummy has to follow all of them making it look funny when it tries to follow the player. My questions are:
Is there any way to get around this without using a while loop?
Are there any improvements or things i should add to this script?
Feedback is much appreciated, thank you for your time