 # Quick question: how to get the nearest player to a certain position?

I’m unsure how to do this and I’ve tried numerous things which didn’t work…

Something like that? Or did I misunderstand?
[lua]function GetNearestPlayer(vector)
local closest = false
local closestdistance = math.huge()
for k,v in ipairs(player.GetAll()) do
local distance = vector:Distance(v:GetPos())
if distance < closestdistance then
closestdistance = distance
closest = v
end
end
if closest then return closest end
end[/lua]

:ninja: :ninja: :ninja: :ninja: :ninja: :ninja:

Theres different things you can try.
For once, you can loop through all of the players, and check their distance to the pos, which would look like this:

``````

local pos = Vector(0,0,0)
local ClosestDistance = 10000000 // Just something incredibly high
local ClosestPlayer = NULL
for _,v in pairs(player.GetAll()) do
local Distance = v:GetPos():Distance(pos) // I prefer saving the distance seperately than calculating it a new each time, since it's computationally expensive to get the distance in 3D space
if Distance < ClosestDistance then
ClosestDistance = Distance
ClosestPlayer = v
end
end

``````

Edit:
Oh well, got ninja’d.

Well, I figured it out myself and was about to post my solution. (it’s shockingly similar!)
[lua]local NearestPlayer = NULL
local LowestDist = math.huge
for _, v in pairs( player.GetAll() ) do
local Dist = ( Pos - v:GetPos() ):Length()
if ( Dist < LowestDist ) then
LowestDist = Dist
NearestPlayer = v
end
end[/lua]
But thanks anyway!