How do I find the nearest player from a block?

So I am trying to create an attack sort of function where when you press a button, something happens to the nearest player of a certain block

So far I have the UI button connected to fire a remote event so that this attack can happen, although I’m very lost on how to find the nearest player from the block. I tried scripts from Scripting Helpers but they weren’t working and I didn’t understand how to apply it to my script.

This is my script right now:

local rep = game:GetService("ReplicatedStorage")
local event = rep:FindFirstChild("ControlPanelEvents")
local block = game.Workspace.CORE.Part1

event.Attack1.OnServerEvent:Connect(function()
	print("fired")
	local function FindNearestPlayer(block)
		local found
		local last = 0
		for i,v in pairs(game.Players:GetPlayers()) do
			local distance = v:DistanceFromCharacter(Vector3.new(block.Position))
			if distance < last then
				found = v
			end
			last = distance
		end
		return found
	end
	
	print(FindNearestPlayer(block))
end)

Hope someone can help :slight_smile:

4 Likes

Took your code and fixed it up. While doing so, I found out the issue.

local rep = game:GetService("ReplicatedStorage")
local event = rep:FindFirstChild("ControlPanelEvents")
local block = game.Workspace.CORE.Part1

local function FindNearestPlayer(position)
	local found
	local last = math.huge
	for _,plyr in pairs(game.Players:GetPlayers()) do
		local distance = plyr:DistanceFromCharacter(position)
		if distance < last then
			found = plyr
			last = distance
		end
	end
	return found
end

event.Attack1.OnServerEvent:Connect(function()
	print("fired")
	print(FindNearestPlayer(block.Position))
end)

There was a small logical error in the algorithm. The line last = distance should be placed inside of the if statement, as we want to compare the current most closest player (aka found) and not the previously checked distance. If you put it in the if statement, last (a distance) is now linked to found.

Also, we need to set the initial value of last to math.huge as we want the closest player. Setting it to 0 would make the loop think that there is already a closest player (with 0 being the most closest you can get) which is not the case. math.huge will ensure that no matter the distance, the first player will be put as found and the last (a distance) will be updated. This found variable will be changed, of course, if someone closer was found.

3 Likes

Works perfectly, thank you so much!

1 Like