Is there any order to GetPartBoundsInBox return array?

I have been working on custom physics engine with custom collisions and bunch and I was wondering if there is any order that GetPartBoundsInBox returns intersected parts in, specifically if they are ordered in closest to furthest.

It could be quite and useful feature where there could be some kind of sort enum for different ordering (closest-furthest, furthest-closest).

Here is the code where I would need this kind of feature.

function physicsSolver:GetClosestTo(vectorPosition, vectorInstanceArray)
	local closestInstance = vectorInstanceArray[1]
	local closestDirection = (vectorPosition - closestInstance.Position)
	local closestDistance = closestDirection.Magnitude
	
	--// TODO: Figure out if there is any order of GetPartBoundsInBox array.
	for index = 2, #vectorInstanceArray do
		local instance = vectorInstanceArray[index]
		
		local direction = (vectorPosition - instance.Position)
		local distance = direction.Magnitude
		
		if closestDistance > distance then
			closestInstance = instance
			closestDirection = direction
			closestDistance = distance
		end
	end
	
	--// Too many return values, distance can be easily computed
	return closestInstance, closestDirection
end

function physicsSolver:IsPositionInSolid(vectorPosition, boundingBox)
	local objectsInSpace = workspace:GetPartBoundsInBox(CFrame.new(vectorPosition), boundingBox, self.Env:GetOverlapParams())

	if #objectsInSpace > 0 then
		--// Done for engine edge-cases.
		local closestInstance, closestDirection = self:GetClosestTo(vectorPosition, objectsInSpace)

		return closestInstance, closestDirection, objectsInSpace
	else
		return
	end
end

There is no evidence to support an order based on distance from the centre of the bounding box. You will have to implement this yourself. I would recommend creating a ready-use predicate function for table.sort that sorts based on ascending/descending position, or using a custom enum to redefine what the function should do with the collision results. This will help you generalize the function while also keeping its features context specific (aka. removing redundancy)

2 Likes