You could get the nearest player by using tables and the table.sort() method:
local SearchDistance = 10000
local NPC = script.Parent
local HRP = NPC.HumanoidRootPart
local Humanoid = NPC:FindFirstChildOfClass("Humanoid")
local function getNearestPlayer()
local playerDistances = {}
if HRP then
for i, player in pairs(game.Players:GetPlayers() do
local distance = player:DistanceFromCharacter(HRP.Position)
table.insert(
playerDistances,
{
player,
distance
{
)
end
end
if #playerDistances >= 1 then
table.sort(
playerDistances,
function(a, b)
return a[2] < b[2]
end
)
for i, dataTable in pairs(playerDistances) do
local player = dataTable[1]
local distance = dataTable[2]
if player and distance then
if i == 1 and distance < SearchDistance then
return player
end
end
end
end
end
while HRP and Humanoid.Health > 0 do
wait(1)
local nearestPlayer = getNearestPlayer()
if nearestPlayer then
print("player nearby:", nearestPlayer)
end
end
Now with this you can figure out to stop the NPC from going over the radius. I have to go rn, attempt it and if you need any help leave a comment.
4 comments
just to clarify, you want the npc walking towards the player?
lol, he specifically stated in the question for the npc to walk within a certain radius of the player, but not to the exact location of the player
yes, but within a radius of like 10 bricks, i want NPC to stop within that radius, please answer this
serpentine im sorry, i was CLARIFYING with COMMANDER tyvm