How can I accurately convert the 2d area of a UI Frame to a Region3?
Ok, so to start off, what I am trying to do is find all of the parts in the 3d game world that a 2d UI Frame would theoretically contain based off of the camera's rotation, field of view, and such if the 2d UI Frame was given a 3d coordinate, and a depth-axis that extends back about 1000 studs.
The method I have coded to do so involves creating two rays at the upper and lower corners of the UI Frame, and creating a Region3
from there, and using the function Workspace:FindPartsInRegion3()
to get all of the parts that the UI Frame would theoretically contain if it were converted to a 3d Region3
with the conditions previously stated above.
Here is my code:
01 | local function GetPartsInUI(ui) |
02 | local cam = game.Workspace.CurrentCamera; |
03 | local min_corner = ui.AbsolutePosition; |
04 | local max_corner = ui.AbsolutePosition + ui.AbsoluteSize; |
05 | local r 1 = cam:ScreenPointToRay(min_corner.X, min_corner.Y, 5 ); |
06 | local r 2 = cam:ScreenPointToRay(max_corner.X, max_corner.Y, 5 ); |
07 | local pos 1 = CFrame.new(r 1. Origin, (r 1. Direction - r 1. Origin).unit); |
08 | local pos 2 = CFrame.new(r 2. Origin, (r 2. Direction - r 2. Origin).unit); |
09 | pos 1 = pos 1 - (pos 1. upVector * 999 ); |
10 | local pos 1 _sum = pos 1. p.X + pos 1. p.Y + pos 1. p.Z; |
11 | local pos 2 _sum = pos 2. p.X + pos 2. p.Y + pos 2. p.Z; |
12 | local reg 3 = Region 3. new(( function () |
14 | if pos 1 _sum > pos 2 _sum then |
23 | local parts = game.Workspace:FindPartsInRegion 3 (reg 3 , nil , math.huge ); |
My problem is that half of the time the parts inside of the UI Frame are not recognized to be inside of the Region3.
I am assuming that this is either due to my setting up of the position (pos1 and pos2) variables, or an issue with the rays returned from the :ScreenPointToRay()
function.
With all of that being said, please tell me what am I doing wrong, and how can I improve upon this???
Thanks