✓ Accepted answer
Question
Detector that can detect a player if the player is near?
Solution
Basis of Solution
Iterate over the players that are currently in game, get their character, and get the distance from their character to your character.
You can get the distance from your character and someone else's character 2 ways.
- (Position1 - Position2).Magnitude
- Player:DistanceFromCharacter(Position2)
I personally would use Player::DistanceFromCharacter because you have to make less references on the front-end Lua side.
The documentation for Player::DistanceFromCharacter is available here: https://developer.roblox.com/en-us/api-reference/function/Player/DistanceFromCharacter
Elaboration
You will want to sort the distances from everybody, and then pick the closest one. An easy way to do this is using table.sort. Given the name of table.sort, you would likely want to store the distances in a table! You can pass a function to table.sort which will determine how to sort it. In this case we can just have the closest player be the 1st index.
Pseudo Code Example
local client =
local playersIngame = playersService:GetPlayers()
local nearPlayers = {}
local maxDistance = 50
for i, player in players(playersIngame)
local character = player.Character
if (character and (player ~= client)) then
local head = character:WaitForChild("Head")
local distance = client:GetDistanceFromCharacter(head.Position)
if (distance <= maxDistance) then
nearPlayers[#nearPlayers + 1] = {
player = player,
distance = distance
}
end
end
end
table.sort(nearPlayers, function(playerA, playerB)
return playerA.distance < playerB.distance
end)
local nearest = nearPlayers[1].player
For a more elaborated answers/more documented answers try reading these threads:
https://devforum.roblox.com/t/checking-nearby-humanoids/200393
https://scriptinghelpers.org/questions/54060/how-do-i-use-magnitude-to-find-the-nearest-player-in-the-game
https://devforum.roblox.com/t/what-is-the-quickest-way-to-see-which-player-is-closest-to-a-position/342962
1 comment
Please use code blocks and not pictures to show your code.