How to detect the nearest player from a part?

Basically im trying to make it so that whenever you’re nearest to a part, The script does stuff. But whenever i test it doesn’t work, No errors and no prints.

game.Players.PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(char)
		while math.floor(game.Workspace.StarterCharacter.HumanoidRootPart.Velocity.Magnitude) > 0 do
			wait(1)
			local nearestPlayer, nearestDistance
			local e = 
			for i, v in pairs(game.Players:GetPlayers()) do
				local part = game.Workspace.StarterCharacter.Hitbox
				print("works")
				local maxDistance = 50
				local distance = plr:DistanceFromCharacter(part.Position)
				print("works")
				if not char or
					distance >= maxDistance or
					(nearestDistance and distance >= nearestDistance)
				then
                   -- doing stuff
					continue
				end
				nearestPlayer = plr
				nearestDistance = distance
			end
			print("The nearest player is".. nearestPlayer)
		end
	end)
end)

Explanation


  1. I add every player and their distance from the part into 1 table.
  2. I sort the table
  3. I return the 1st player (Which is the lowest number)

My Script


• Just finding the closest:

function GetClosestPlayerFromObject(object)
	local InRange = {}

	for _, player in pairs(game.Players:GetPlayers()) do
		table.insert(InRange, {Player = player, Range = (object.Position - player.Position).Magnitude}) -- Adds player
	end
	
	table.sort(InRange, function(A,B) return A.Range < B.Range end) -- Change < to > if it's not ascending
	
	return InRange[1].Player -- Returns the closest player
end

local ClosePlayer = GetClosestPlayerFromObject(MyObject)

• Finding the closest within a range:

function GetClosestPlayerFromObject(object)
	local InRange = {}
	local MaxRange = 50
	
	for _, player in pairs(game.Players:GetPlayers()) do
		if (object.Position - player.Position).Magnitude <= MaxRange then
			table.insert(InRange, {Player = player, Range = (object.Position - player.Position).Magnitude}) -- Adds player
		end
	end

	table.sort(InRange, function(A,B) return A.Range < B.Range end) -- Change < to > if it's not ascending

	return InRange[1].Player -- Returns the closest player
end

local ClosePlayer = GetClosestPlayerFromObject(MyObject)
5 Likes

Hey, I’m sorry but i don’t really know what to change in the script.

Change this symbol if it's not working correctly


table.sort(InRange, function(A,B) return A.Range < B.Range end)

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.