I'm making a turret that fires at people when they get too close. Is there an easy way to find the nearest player to the turret?
How do I find the nearest player?
2 answers
what i would do is make a table of all the players within the zone, and constantly check the positions of the player and the player that is the closest will be the target, this is most likely a inefficient way to do it, im open to suggestions from other people on better ways, if any, to get closest player
I did do this with a creepy eye project of mine before, just drop me a PM if you want the model
3 comments
Nah. It's pretty efficient. Just specify you mean Player's character, not the player itself. Also you can get a table of players with game.Players:GetPlayers()
yeah but the OP specified he wants players within a zone, so i was thinking of putting players that touched a brick in a table, but it gave me alot of headaches with debugging so i just chose to limit the zone with the magnitude of a raycast
Heres what i made cause i wanted to improve on my poorly written code in my creepy eye project lol: https://gyazo.com/b8f549280367d38efd460e9d01a5b622
Here's a sample of how to find the nearest character:
local point = workspace.Turret --for example
local closest
local last = 0
for _,v in pairs(game:GetService("Players"):GetPlayers()) do
local magnitude = (point.Position - v.Character.HumanoidRootPart.Position).magnitude
if magnitude < last then
closest = v
end
last = magnitude
end
This discussion is preserved as it was. New answers, comments, and votes are closed.

1 comment
Loop through all the players and use .Magnitude to get the distance. https://www.robloxdev.com/articles/Magnitude