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

I'm trying to find the nearest player/npc, any help?

local range = 50
local closest
for _, child in pairs(workspace.alive:GetChildren()) do
	local success, rootPart = pcall(function()
		return child.Humanoid.Health > 0 and child.HumanoidRootPart
	end)
	if success and child ~= character then
		local distance = (rootPart.Position - character.HumanoidRootPart.Position).magnitude
		if distance < range then
			range = 0
			closest = rootPart
			print(closest.Parent.Name)
		end
	end
end

http://prntscr.com/ox630j

I'm trying to get the nearest player/npc, but this is always going to give me the first player/npc listed in the "alive" folder. Any help?

1 answer

..why do you set range to 0? the range sould be set to distance to signify that your code should be measuring under. setting it to 0 means that nothing can be lower (as magnitude is rarely a negative value, distance is only measured positively, you can't be -400 miles away from someone.)

you should do something along the lines of this:

function getNearest(r, search)
	r = r or 50; --set range to a default if it is undefined
	
	local nearest;
	for _, v in pairs(search:GetChildren()) do --make the function a bit more flexible
		local hum = v:FindFirstChild("Humanoid");
		local dist = (v.PrimaryPart.Position - character.PrimaryPart.Position).Magnitude; --get the distance between point a and point b via magnitude
		if (hum and hum.Health > 0) and (dist <= r) then --lessen the strictness by making it <= instead of <
			r = dist; --set the range to distance so we now have a lower maximum to search under
			nearest = v; --self-explanatory
		end
	end
	local signifier = not nearest and warn('unable to find nearest humanoid.')
	return nearest;
end
p.s. i like your name lol
p.p.s, welcome to scriptinghelpers!

2 comments

1

Thank you! 8)

0

HHAHAHHAHAHAH WHY U ANSWeRING QUESTIONS IN 2019 BRO LIK WUT BRO WUT UR DOING WITH UR TIM BRUV LIEK BROOOOO. HAHAHHA EPIC TROLE TROLE TROEL HAHASHAT ROLE TORLE LMAOF LMOAF

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