Someone asked me if you could optimize XAXA’s function, so I’ve made this version which is slightly faster (according to my benchmarks, ~1 second when called 10 ^ 7 times), for those interested:
-- It's faster to localize object methods
local Methods = Instance.new('Part')
local IsA = Methods.IsA
local GetDescendants = Methods.GetDescendants
-- Same goes for CFrame methods
local CFMethods = CFrame.new()
local ToObjSpace = CFMethods.toObjectSpace
local GetComponents = CFMethods.GetComponents
local PointToWorldSpace = CFMethods.PointToWorldSpace
local inf = math.huge
local negInf = -inf
function GetBoundingBox(model, orientation)
-- ternary is faster according to my benchmarks
model = type(model) ~= 'table' and GetDescendants(model) or model
orientation = orientation or CFMethods
local minx, miny, minz = inf, inf, inf
local maxx, maxy, maxz = negInf, negInf, negInf
-- next is just my preference, LuaU optimized next and pairs out anyway
for _, obj in next, model do
-- localization of IsA method
if IsA(obj, 'BasePart') then
local cf = ToObjSpace(orientation, obj.CFrame)
local size = obj.Size
local sx, sy, sz = size.X, size.Y, size.Z
-- Localization of GetComponents
local x, y, z, R00, R01, R02, R10, R11, R12, R20, R21, R22 = GetComponents(cf)
-- LuaU optimizes out localization of global table indexing (such as math.abs);
-- localization is actually slower in this case!
local wsx = 0.5 * (math.abs(R00) * sx + math.abs(R01) * sy + math.abs(R02) * sz)
local wsy = 0.5 * (math.abs(R10) * sx + math.abs(R11) * sy + math.abs(R12) * sz)
local wsz = 0.5 * (math.abs(R20) * sx + math.abs(R21) * sy + math.abs(R22) * sz)
-- ternary is faster according to my benchmarks
minx = minx > x - wsx and x - wsx or minx
miny = miny > y - wsy and y - wsy or miny
minz = minz > z - wsz and z - wsz or minz
maxx = maxx < x + wsx and x + wsx or maxx
maxy = maxy < y + wsy and y + wsy or maxy
maxz = maxz < z + wsz and z + wsz or maxz
end
end
-- removed redundant variable definitions that are only used once
local omin, omax = Vector3.new(minx, miny, minz), Vector3.new(maxx, maxy, maxz)
-- swapped / 2 to * 0.5, as multiplication is faster. This is nitpicking at this point tho lol
return orientation - orientation.p + PointToWorldSpace(orientation, (omax + omin) * 0.5), (omax - omin)
end
Unsure why you would need something optimized to this extent, since if you even need to optimize you’re probably doing something wrong, but here you go (sorry to bump btw).
EDIT: Fixed an issue where the results weren’t consistent with @XAXA’s original code… Really sorry about that. Also optimized it out a bit more.