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

How do I make a specific player find the nearest player?

Asked by 4 years ago

I am trying to learn magnitude and I'm very new to it. If so, where should I begin?

1 answer

Log in to vote
1
Answered by 4 years ago

Here's a quick script I wrote to help you understand magnitude.

local PlayerObject = game.Players:WaitForChild("PlayerName") --//Change PlayerName to the name of the specific player you want
repeat wait() until PlayerObject.Character ~= nil --//Making sure the player's character isn't nil when we set the CharacterObject variable

local CharacterObject = PlayerObject.Character

local FoundPlayer, Closest = nil, math.huge --//Setting the variables that will help us find the closest other player

for _, v in pairs(game.Players:GetPlayers()) do --//Gotta loop through the players
    if (v ~= PlayerObject and v.Character) then --//Making sure that the player we're looping through is not the player we specified, otherwise it would cause a bug
        local Distance = (CharacterObject.PrimaryPart.Position - v.Character.PrimaryPart.Position).Magnitude --//To get the distance between two parts, you get the difference of their positions and call the magnitude property on the new vector
        if (Distance <= Closest) then --//Checking to see if the closest is more than the distance we calculated, if it is we have a new closest
            --//Just updating the closest value and the FoundPlayer value incase this is the closest player we could find
            Closest = Distance
            FoundPlayer = v
        end
    end
end

--//Just printing out the closest player's name
if (FoundPlayer) then
    print("The closest player was " .. FoundPlayer.Name .. " at " .. Closest .. " studs away!")
end
0
What if I want it to be teams? User#27966 0 — 4y
0
On line 9, just change it to this: if (v~= PlayerObject and v.Character and v.Team == game:GetService("Teams"):FindFirstChild("TeamName")) then --//Change TeamName to the name of the team you want the closest player to be CeramicTile 847 — 4y
0
Thank you so much! User#27966 0 — 4y
0
Np, if you have any more questions we're here to help you! CeramicTile 847 — 4y
Ad

Answer this question