Hello, I am trying to figure out (with no luck) how to get a 2d bounding box of a 3d object. I would like to give the object in 3d space as the parameter for the function and have it return a 2d rect which represents the bounding box of the 3d object, or at least the part that is on screen.
Said more simply, I would like to create a 2d rect that covers up a 3d object where ever it goes.
Create Rect class that has an X and Y of the lowest X and Y values, and a width and height of the highest X and Y values minus the Lowest X and Y values.
Makes sure those values are using localPosition and not Global Position.
Use Rectangle to check 2D box coordinates.
Using Unity:
Get Extents.
Get Centre of Rectangle (Centre X is largest X + Smallest X / 2, same for Y)
Get difference between smallest and largest X and Y values.
Create BoxCollider
Set to IsTrigger
Centre is the Centre you calculated (z is 0)
Size is the Difference You Calculated (z is 1, or 0.1 or whatever you like).
Use Raycasts and OnTriggerEnter to determine collisions.
I think the OP wants to compute an AABB corresponding to the object’s screen-space projection. Is that what your solution is intended to do? (I couldn’t quite tell…)
@The OP: Here’s one way you could proceed (maybe there’s a more straightforward approach, but it’s not coming to me at the moment):
Get the bounds from the mesh (I assume your object has a mesh associated with it).
Compute the 8 corners of the AABB (you can use the ‘min’ and ‘max’ points or the center and extents for this).
Project the corners to screen space.
Compute the AABB of the projected points.
Unless I missed something, that should give you a screen-space rectangle that completely covers/encloses the object.