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

How can I get the closest character to the player?

I've been messing around with this script for a bit, until I finally realized I can't use table.sort() on a table of objects (the characters). So after that revelation, I realized I needed a way to return the character and also sort a table to get the smallest distance with the first index.

Any ideas? I'm stumped.

local function GetClosestCharacter()
	local distTable = {}
	for i, plr in pairs (Players:GetPlayers()) do
		if plr ~= Player then
			if Functions.IsTeamMate(plr, Player) then 
				if plr.Character and Character then 
					local distance = (plr.Character.HumanoidRootPart.Position - Character.HumanoidRootPart.Position).Magnitude
					if distance <= Configuration.HealMaxDistance.Value then  
						table.insert(distTable, i, plr.Character) 
					end
				end
			end
		end
	end
	table.sort(distTable)
	return distTable[1]
end

Heres what I had so far, which obviously trying to compare objects is syntactically incorrect, I just cant think of a way to return the character with the shortest distance to the player.

1 comment

0

lol i promise that indentation isnt my fault; rip text editor on SH, needs a larger window lul

1 answer

✓ Accepted answer

well, you can have two variables at the top of the function that both represent the ClosestCharacter and the ClosestDistance.

--just a proof of concept
local distTable = {0,1,1,2,3,5,8}
local ClosestDist,ClosestChar = math.huge

for i,dist in distTable do
	if dist<ClosestDist then
		ClosestChar = i
	end
end
print(ClosestDist,ClosestChar) --0, 1

This, applied in your example, could be similar to:

local function GetClosestCharacter()
	local closestDist,closestChar = math.huge
	for i, plr in pairs (Players:GetPlayers()) do
		if plr ~= Player then
			if Functions.IsTeamMate(plr, Player) then 
				if plr.Character and Character then 
					local hrp = plr.Character.HumanoidRootPart
					local hrp2 = Character.HumanoidRootPart
					local distance = (hrp.Position - hrp2.Position).Magnitude
					if distance <= Configuration.HealMaxDistance.Value then  
						if distance < closestDist then
							closestDist,closestChar =distance,plr.Character
						end
					end
				end
			end
		end
	end
	return closestChar
end

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