Hello. I have been struggling with a problem and i’m hoping someone could provide me with a solution or with more information on how I might figure this out. What i’m trying to do I thought would be fairly simple, but has turned out to be a lot more complicated than I originally thought. I have a quad plane that exists in my game world, and what i’m trying to do is draw a Camera rect around this quad based on its screen position and to make sure that the quad is always fully encapsulated within that rect.
Here is an example of what I’m describing:
In this image I have the plane and I have manually drawn a red square to indicate the rect on the screen that it fills up.
I was able to achieve this easily with camera.worldToScreen
, however I quickly discovered when points are off of the screen this causes issues. Thankfully I found a blog post by someone else who was also trying to do something similar here: A Solution To Unity's Camera.WorldToScreenPoint Causing UI Elements To Display When Object Is Behind The Camera
However, the solution he provided does not work in all cases. For example, when the camera gets extremely close to the plane, values can get really weird and don’t behave the way I expected. It gets difficult to tell whether I should set the bounds of the rect all the way to the sides of the screen or not. For example, take a look at this possibility: (I tried to link another image but since I’m a new user it won’t let me. I will try to post the images in the following forum message if the website lets me)
In this case, the square covers most of the screen with the edge being the point visible. However if the player or camera moves ever so slightly a different rect needs to be drawn:(I tried to link another image but since I’m a new user it won’t let me. I will try to post the images in the following forum message if the website lets me)
Describing the exact math and how the points change from the worldToScreen
function is difficult to describe. Its clear that the point “flips” around when it goes behind the camera, but since the points are on the same plane they can end up returning to almost use able coordinates again. For example in that previous image, the “top right” corner of the plane is not visible and is behind the camera. But its screen position might be something like (-400, 100, -1.0) which I believe can be useful although I haven’t quite figured out how.
I have tried multiple ways off trying to discern a “pattern” to determine what the size of the rect should be, but I haven’t had any lucking finding a solution. Does anyone have any ideas or tips that I can use to try and get this working correctly?