Need help finding the closest part to another

So basically, In my game I’m doing a push ability that launches a character within the range (in studs) of 3.4. I have a recurring problem with this though, in the code I have a ‘for’ loop that goes through each model in game.Workspace, checks if it has a Humanoid and then puts a BodyVelocity in the HumanoidRootPart but it doesn’t throw the closest (which I want to do).

local Char = Player.Character
local Torso = Char:FindFirstChild("Torso")

local ForceMultiplier = script:FindFirstChild("Force") -- 1
local RangeMultiplier = script:FindFirstChild("Range") -- 1

local RangeStuds = 3.4

for i, v in pairs(workspace:GetDescendants()) do
	if v ~= Char then
		local _Hum = v:FindFirstChild("Humanoid")
		local _Root = v:FindFirstChild("HumanoidRootPart")
		if v:IsA("Model") and _Hum ~= nil and _Root ~= nil then
			if (_Root.Position - Torso.Position).Magnitude <= RangeStuds * RangeMultiplier.Value then
				-- Code
			end
		end
	end
end

Is there any way to alter the for loop to only run the code on the closest HumanoidRootPart?
Thanks

Nevermind, somebody has already solved this.

1 Like

If you have millions of descendants in workspace you should not be doing it like this.

A still naïve, but much more performant solution is to use the spatial query API.

WorldRoot:GetPartBoundsInRadius(Vector3 position, float radius, OverlapParams overlapParams)

local Params = Instance.new("OverlapParams")
local Parts = Workspace:GetPartsInRadius(Torso.Position, RangeStuds, Params)

table.sort(Parts, function(A, B)
    return Player:DistanceFromCharacter(A) < Player:DistanceFromCharacter(B)
end)

local ClosestPart = Parts[1]

An even better option for static maps, or relatively ones, is quad trees.

2 Likes