I’m trying to sort a table of instances for a camera targeting feature, and it works fine as long as they’re being looked at. The only problem I’m getting right now is that if I turn the camera away from the parts, they no longer exist. Here’s the function I’m using to sort them:
If I look in the opposite direction of anything in self.Targetable, either a or b becomes nil.
self.Targetable is a table defined as CollectionService:GetTagged("Targetable") that is updated ever 2 seconds.
if #self.Targetable >= 2 then
table.sort(self.Targetable, function(a, b)
-- print(a, b)
if a == nil then return false end
if b == nil then return true end
if a == nil and b == nil then return true end
local scA, osA = camera:WorldToViewportPoint(a.Position)
local scB, osB = camera:WorldToViewportPoint(b.Position)
if not osB then
return true
elseif not osA then
return false
end
local v2a = Vector2.new(scA.X, scA.Y)
local v2b = Vector2.new(scB.X, scB.Y)
local cpos = Vector2.new(camera.ViewportSize.X/2, camera.ViewportSize.Y/2)
if (cpos-v2a).Magnitude < (cpos-v2b).Magnitude then
return true
else
return false
end
end)
end
Here’s a video illustrating the problem. Notice how the errors start piling up once any of the golems are not in frame, since the sort function is being ran on RunService.Heartbeat. Right now, the error is invalid order function for sorting because it’s returning in one of the 3 sanity checks at the start of the function where something is being passed as nil, but would error out as a is a nil value or b is a nil value otherwise.
(please excuse the sad boi rap i was listening to when documenting this bug)
External Media