0
\$\begingroup\$

I have placed three game object in the scene.How to know whether the object is visible on the screen.Print a message if the object is not visible on the screen.

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

Take in mind, I'm not a big Unity user, however I can give you an answer, that works pretty much everywhere.

Prerequisits: you need to know the x and y FOV angle of the camera (you can calculate the x by taking the y FOV and multiplying it with the aspect ratio of the device), and the euler angles of the camera.

Create a vector, which points from the camera to the object you want to check against, then you can get the absolute angle of this vector with the following formula:

r := sqrt(x² + y² + z²)
yAngle := arctan(y / x)
xAngle := arccos(z / r)

Now, you know the absolute angles of the vector.

You need to divide the x and y angles of the camera from the x and y angles of the vector, this way you get the angles relative to the camera.

Here comes the trick: if the relative x and y angles are between the negative xFov and yFov and positove xFov and yFov (add some falloff to it of course), then it's inside the view of the camera.

However, this has some cons. The biggest and most obvious is that if your object is very big or is very close to the camera, then you can get false results. This can be solved by giving it a bigger falloff, but that won't work if you object likes to get close to the camera and then get far again, then this won't work either.

In cases like that, you should simply render it to a texture, and check if it is on it.

\$\endgroup\$
1
\$\begingroup\$

Unity has built-in methods to detect it. It's called the same way as OnTriggerEnter.

public class Invisibility : MonoBehaviour {
    void OnBecameInvisible() {
        Debug.Log("I`m gone :(");
    }
    void OnBecameVisible() {
        Debug.Log("Hi, I`m back!");
    }
}

Note: that if the object is visible on the Scene view OnBecameInvisible won't be called. Same way with OnBecameVisible - if it becomes visible on the Scene view. After building your game it shouldn't bother you, this only exists in the editor.

1) Renderer.OnBecameInvisible 2) MonoBehaviour.OnBecameInvisible

If you want to check if the gameobject is currently visible you can get his Renderer.isVisible (it returns true if the shadow is rendered).

If you want to detect via bounding box falls within a frustum of a camera, later you have to check if it's not blocked by any object via Raycasting.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .