Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I find the nearest player?

Asked by
Jexpler 63
5 years ago

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?

0
Loop through all the players and use .Magnitude to get the distance. https://www.robloxdev.com/articles/Magnitude MythicalShade 420 — 5y

2 answers

Log in to vote
0
Answered by
aazkao 787 Moderation Voter
5 years ago
Edited 5 years ago

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

0
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() Vezious 310 — 5y
0
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 aazkao 787 — 5y
0
Heres what i made cause i wanted to improve on my poorly written code in my creepy eye project lol: https://gyazo.com/b8f549280367d38efd460e9d01a5b622 aazkao 787 — 5y
Ad
Log in to vote
0
Answered by 5 years ago

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

Answer this question