Find the nearest player

How do I find the nearest player to a part but within a radius of 10blocks?
I know you would need to do magnitude and something but i have no idea how to start or do any of it.
Please help.

6 Likes

Since you already have the part and the radius planned out, all you have to do this is this

Loop so that every once in a while (or every frame if you require), loop through all the players via game:GetService("Players"):GetPlayers(), then do the following

  • Check if their character exists and if it doesn’t, ignore them
  • Check if their distance from the part is less than or equal to 10 AND their distance is smaller than the previous smallest distance, if it is, store the player and their distance in variables
  • Repeat for all players

Then at the end you just print out the nearest player

Something like this to give out an example

local Players = game:GetService("Players")

local part = --Your part

local maxDistance = 10

while true do
	wait(1)
	local nearestPlayer, nearestDistance
	for _, player in pairs(Players:GetPlayers()) do
		local character = player.Character
		local distance = player:DistanceFromCharacter(part.Position)
		if not character or 
			distance > maxDistance or
			(nearestDistance and distance >= nearestDistance)
		then
			continue
		end
		nearestDistance = distance
		nearestPlayer = player
	end
	print("The nearest player is ", nearestPlayer)
end
37 Likes

How would i do this for a local script finding the nearest player for the player it is parented to