What is the easiest way to get the closest player to you in clientside lua?
Loop through them, get their positions, and find their distance from you. Make sure you use Vec1:DistToSqr(Vec2) instead, because the Distance method is expensive.
I can’t think of a better way than looping through all players that aren’t you and checking their distance:
for k,v in pairs(player.GetAll()) do
if v~=ply then
if not closestdist then
if dist<=closestdist then
Untested, but should work
edit: updated with crazyscouters tip about DistToSqr
It’s just returning myself, and there are other players.
function GetClosestPlayer(ply) local closestply local closestdist for k, v in pairs(player.GetAll()) do if v ~= ply then local dist = ply:GetPos():DistToSqr(v:GetPos()) print(dist) if not closestdist then closestdist = dist end if dist <= closestdist then closestply = ply end end end return closestply end print(GetClosestPlayer(LocalPlayer()):GetName())
[editline]19th July 2015[/editline]
Your code was broken, I just fixed it -_-
if dist <= closestdist then closestply = v end
Whoops, as I said it was untested - but good to see you got it working
I never knew DistToSqr existed.
Is there any case where I would use Distance over DistToSqr?
If you want to actually know the distance instead of just compare, e.g. to display distance from an object on a player’s screen.
Like when you absolutely need the distance, and not the squared distance?
Only really for human readable things like HUD or messages.
Replaced all my Distance checks with DistToSqr and it has given me a nice little boost in performance.
The solution you got is good, but I’ll throw in what I use personally.
function ARCLib.GetNearestPlayer(pos,plyex) – Gets the nearest player relative to pos. plyex is the player to exclude.
local dist = math.huge
local ply = NULL
for _, v in pairs( player.GetAll() ) do
local newdist = pos:DistToSqr( v:GetPos() )
if newdist < dist && v != plyex then
ply = v
dist = newdist
You can remove the “ARCLib.” part, I just copy/pasted it from my bag-o-functions.
If you wanted the closest player to you, you can call GetNearestPlayer(LocalPlayer():GetPos(),LocalPlayer())
I personally think this is more useful as you can get the nearest player to any location, not just yourself.