NPC Follow
local NPC = script.Parent
local Humanoid = script.Parent:FindFirstChild(“Humanoid”)
local HRP = script.Parent:FindFirstChild(“HumanoidRootPart”)
local function GetClosestPlayer(range)
local List = {}
local Target = nil
for i, v in pairs(game.Players:GetPlayers()) do
local dist = v:DistanceFromCharacter(HRP.position)
if dist <= range then
table.insert(List, {dist, v})
end
end
table.sort(List, function(A, B)
return A[1] < B[1]
end)
pcall(function()
Target = List[1][2]
end)
return Target
end
while true do
wait()
local Target = getClosestPlayer(30) -- // change 30 to the max distance
if Target == nil then return end
Humanoid:MoveTo(Target.PrimaryPart)
Humanoid.MoveToFinished:Wait()
end
版权声明: 本文为 InfoQ 作者【katichar】的原创文章。
原文链接:【http://xie.infoq.cn/article/e6ec97cf8ab9d50769da429a5】。文章转载请联系作者。
评论