Hello, does anyone know how to detect all players near a player. For example, if a player presses a button, it will get all the nearby players within a certain radius, and it will damage them.
4 Likes
local function GetPlayersWithinDistance(from : Vector3, distance : number)
local t = {}
for _, v in pairs(game.Players:GetPlayers()) do
if v.Character and v:DistanceFromCharacter(from) < distance then
table.insert(t, v)
end
end
return t
end
print(GetPlayersWithinDistance(part.Position, 10)) -- prints all players within 10 studs of the part
7 Likes
local players = game:GetService("Players")
local function getCharactersWithinDistance(player, maxDistance)
local foundCharacters = {}
if not player then return end
local character = player.Character
if not character then return end
for _, otherPlayer in ipairs(players:GetPlayers()) do
if not otherPlayer then continue end
local otherCharacter = otherPlayer.Character
if not otherCharacter then continue end
if not otherCharacter.PrimaryPart then continue end
local distance = player:DistanceFromCharacter(otherCharacter.PrimaryPart.Position)
if distance <= maxDistance then
table.insert(foundCharacters, otherCharacter)
end
end
return foundCharacters
end
5 Likes