Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

1 answer

✓ Accepted answer

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

4 comments

0

What if I want it to be teams?

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

0

Thank you so much!

0

Np, if you have any more questions we're here to help you!

This discussion is preserved as it was. New answers, comments, and votes are closed.