Get closest player to an NPC

0

local npcHRP = NPC.HumanoidRootPart

local function GetNearestPlayer(minimumDistance)
    local closestMagnitude = minimumDistance or math.huge
    --minimumDistance is a number in studs
    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

  • 0 posts
  • 0 subtopics
  • 27 days ago by vince