Best way of checking if you're near another player?

I was wondering what would be the most optimized and best way to go about checking for a player near another player, for interactions like reviving or executing. Here’s an example from Combat Warriors of what I mean:


You can see when I go near a downed player and press the G button, it initiates a glory kill sequence. What would be the best way to check for a player nearby?
Any help is appreciated.

1 Like

Magnitude checking. From player A’s character’s position to player B’s character’s position

3 Likes

Yes, that would be a good way to see if you’re near enough to another player, however, I would have to loop through every player’s character and check the magnitude for each to actually detect the player first, and I feel that isn’t the most optimized way to do this. I might be wrong, though. Is there any other better way?

I would just loop through all the players and see how far you are.

local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:wait()
local root = character:WaitForChild("HumanoidRootPart")

for _, otherPlayer in pairs(game.Players:GetPlayers()) do
  local otherCharacter = player.Character
  if not otherCharacter then continue end
  local otherRoot = character:FindFirstChild("HumanoidRootPart")
  if not otherRoot then continue end

  local dist = (otherRoot - root).Magnitude

  if dist < 10 then
    print(string.format("%s is close (%.1f studs away)", otherPlayer.Name, dist))
  end
end
1 Like

I mean, no? yes there are other ways but I’m not convinced they’ll be faster

It is insanely fast to calculate magnitude. If you have less than 10,000 players in your game it will never show up in your performance monitoring.

1 Like

Using something like Spatial Query could work? Considering you don’t want to check distance from every player

2 Likes

Okay, I was wrong then, I thought that wouldn’t be very optimized. Thanks for the solution.