How to find the closest player

At a part in my game where when the player presses a button the game finds the closest player to them, that is on a different team. how can I do this.

1 Like

You can check the distances with magnitude and check teams with if like:

if Player.TeamColor ~= AnotherPlayer.TeamColor then
    --Code
end
1 Like
function GetClosestOpponentTo(Player, Opponents)
    local Closest = nil
    for  _, Opponent in pairs (Opponents) do
        local OpponentRoot = Opponent:FindFirstChild("HumanoidRootPart")
        local PlayerRoot = Player.Character:FindFirstChild("HumanoidRootPart")
        local Distance = (OpponentRoot.Position - PlayerRoot.Position).Magnitude
  
        if not Closest or Distance < Closest then Closest = Distance end
    end
    return Closest
end
3 Likes

Only issue is there are multiple teams in the game so I can’t put the specific team in parameters.

You can substitute the characters that belong to players from the other team(s) to Opponents.

right but the issue is that I have mutliple teams so how could I do like every team besides the one the player is on.

You can collect the players from all targeted teams (except the player him/herself of course) with Team:GetPlayers() (see Team | Roblox Creator Documentation). Then you can collect their characters and pass them to the function as Opponents.

1 Like