- Home /
See if an object is in a portion of the screen
I'm wondering if there is an easy way to test if an object is in a certain portion of the screen. For example, imagine like a targeting system with a (2D) white square in the middle of a screen, and you want to test that a 3d object from the scene is contained in said square. Raycasting won't really tell me if its contained, so what I really want is like gameObject.boundsOnScreen and then intersect that rect with my 2d rect.
Answer by CHPedersen · Dec 15, 2013 at 12:08 AM
You can obtain the coordinates to each corner of the object's bounding box by working with renderer.bounds. You get two of the corners for free: renderer.bounds.min and renderer.bounds.max. The other 6 can be formed from the coordinates of the first, because the bounding box is axis-aligned. Therefore, if we define:
P0 = renderer.bounds.min
P7 = renderer.bounds.max
Then, the remaining 3 bottom corners of the box are:
P1 = (P0.x, P0.y, P7.z)
P2 = (P7.x, P0.y, P7.z)
P3 = (P7.x, P0.y, P0.z)
And the remaining 3 top corners are:
P4 = (P0.x, P7.y, P0.z)
P5 = (P0.x, P7.y, P7.z)
P6 = (P7.x, P7.y, P0.z)
Once you have the 8 corners of its bounding box, you just convert those to screen space (pixel) coordinates like this:
Vector3 screenSpaceCorner = yourCamera.WorldToScreenPoint(Pi);
Where "i" is the index of the point. The x and y coordinates returned by WorldToScreenPoint is that bounding box corner's pixel position. Compare that against your targeting rect.
Remember that the way you have defined targeting, it seems that you consider the object targeted if only one corner is within the screen space rectangle. Therefore, you should perform the entire analysis for each corner and immediately return true if it's within the rect, skipping further tests. If, for example, the entire object is within the target rect, then the first corner will be enough, since all corners would test true. So you can save a bit of computation that way.
Your answer
Follow this Question
Related Questions
Convert world to screenspace for screenshot of particular object 1 Answer
Scale Gameobject with defined size in pixels 2 Answers
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
prefab is instantiating without a script 2 Answers
how to rotate gameobject only in multiple of 36 degree ? 1 Answer