Hello, I’ve been trying to create a script that will turn true once a specific game object is in a camera’s field of view but I just can’t get it working right. I want the script to turn true only when the selected game object is within the field of view of the camera that holds the script. Check the picture if that doesn’t help.
I tested some script like OnWillRenderObject(), Renderer.isVisible, Renderer.OnBecameVisible, and OnBecameInvisible but nothing seems to works. Maybe something like that:
//This script should be attached to the camera
var Target : GameObject;
function Update ()
{
if (Target.renderer.isVisible)
print ("Visible");
else
print ("Not Visible");
}
But it still doesn’t seem to work, it is visible no mater what because the isVisble command works even if it’s visible by any camera but it’s considered visible when it needs to be rendered in the scene. Any help ?
What exactly are you trying to accomplish (end result)?
Convert the position of the object into viewport space. If the viewport space is within 0-1 you are in the cameras frustum. This method also allows you to add a margin amount if you want, so that objects turn on when they are almost in view.
**EDIT: ** @tanoshimi’s answer is actually a cool alternative. It uses an extension method to give a function to all renderers. http://wiki.unity3d.com/index.php?title=IsVisibleFrom
Just add CameraExtensions.cs to your project and now from any renderer you can call IsVisibleFrom as shown in the example. Not sure if its faster or slower than my solution.
The problem with OnWillRenderObject, Renderer.isVisible etc. is that they test whether an object is visible from any camera, and that includes the editor camera used to render the scene view.
This is a little confusing for me. I'm not familiar with C#. Also i want to be able to choose the object that is in the camera's field of view with ether a variable or tag.
A bit late for this answer, but all you really need is to compute the angle between transform.forward of the camera and the vector to your object, which is derived by subtracting the transform.position (s). You can use Vector3.angle for that. If the resultant angle is less than half the field of view, than your object will be in the field of view.
Correct me if I am wrong, but wouldn't this only work with square camera resolutions? If you are comparing it against the field of view, then that will only be the vertical or horizontal field of view, not both. But as long as you used the larger of the fields of view it should be a good estimate.
What exactly are you trying to accomplish (end result)?
– cryingwolf85