본문 바로가기

Roblox Script

#13 : 따라오는 NPC - npc following

심플한 NPC를 만들고,
MoveTo를 이용해 가장 가까운 플레이어를 찾아서 따라다니는 Script 입니다.

local npcHumanoid = script.Parent.Humanoid
local npcHRP = script.Parent.HumanoidRootPart
 
local function GetNearestPlayer(minimumDistance)
    local closestMagnitude = minimumDistance or math.huge
    local closestPlayer
    for i,v in next, game.Players:GetPlayers() do
        local Character = v.Character
        if (Character) then
            local humanoid = Character.Humanoid
            local HRP = Character.HumanoidRootPart
            if (humanoid.Health  > 0) then
                local mag = (npcHRP.Position - HRP.Position).Magnitude
                if (mag <= closestMagnitude) then
                    closestPlayer = v
                    closestMagnitude = mag
                end
            end
        end
    end
    return closestPlayer
end
 
while true do
 local player = GetNearestPlayer(3000)
 if player then
  print (player.Name)
             npcHumanoid:MoveTo(player.Character.HumanoidRootPart.Position)
 end
 wait(2)
end