Download file:
NPC chase test.rbxl (34.7 KB)
The code will loop through the players and check who is the closest distance away from the NPC. The NPC will chase the closest player using the pathfinding service (made to work in a maze) I’m new to scripting and I’m wondering if there’s a better way to write the code.
local NPC = workspace.NPC
NPC.PrimaryPart:SetNetworkOwner(nil)
local pfs = game:GetService("PathfindingService") -- Pathfinding service
local runService = game:GetService("RunService")
local hum = script.Parent:WaitForChild("Humanoid") -- npc humanoid
local torso = script.Parent:WaitForChild("Torso") -- npc torso
local players = game:GetService("Players")
local distance
local closestPlayer, closestDistance = nil, math.huge
function checkPlayerDistance() -- Function will loop through the players and get the nearest player
local children = players:GetChildren()
for i,v in pairs(children) do
if v then
distance = (v.Character:FindFirstChild("HumanoidRootPart").Position - torso.Position).magnitude
if distance <= closestDistance then
closestDistance = distance
closestPlayer = v
end
end
end
return closestPlayer
end
runService.Heartbeat:Connect(function() -- NPC will follow the nearest player
local returnedPlayer = checkPlayerDistance()
local path = pfs:CreatePath()
path:ComputeAsync(torso.Position, returnedPlayer.Character.HumanoidRootPart.Position)
local waypoints = path:GetWaypoints()
local function npcStuck()
local pos1 = torso.Position
wait(1)
local pos2 = torso.Position
if (pos1 - pos2).magnitude < 1 then
end
end
if waypoints and waypoints[2] then
local pos = waypoints[2]
hum:MoveTo(pos.Position)
end
closestDistance = math.huge
end)