Search Unity

Checking if object is visible to a specific camera

Discussion in 'Scripting' started by eco_bach, Feb 22, 2017.

  1. eco_bach

    eco_bach

    Joined:
    Jul 8, 2013
    Posts:
    1,601
    So after some research I concluded I need to use Physics.Raycast
    https://docs.unity3d.com/Manual/CameraRays.html?_ga=1.75404373.691265055.1483967375

    Following example checks for visibility of an object under the mouse. To make this work with any Game Object you attach it to my assumption is that Input.mousePosition would have to be changed to the x,y screen coordinates of the object and that the the entire contents of the Start() method would need to be in an Update() method.....

    Does this sound correct?

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class ExampleScript : MonoBehaviour {
    6.    public Camera camera;
    7.  
    8.    void Start(){
    9.        RaycastHit hit;
    10.        Ray ray = camera.ScreenPointToRay(Input.mousePosition);
    11.      
    12.        if (Physics.Raycast(ray, out hit)) {
    13.            Transform objectHit = hit.transform;
    14.          
    15.            // Do something with the object that was hit by the raycast.
    16.        }
    17.    }
    18. }
    19.  
    20.  
     
  2. AndyGainey

    AndyGainey

    Joined:
    Dec 2, 2015
    Posts:
    216
    Something like that might sorta kinda work, but it seems a bit backwards, and I don't think the raycast would be needed at all. The raycast is used to find an object, but if you already have an object and want to know if it is visible, there's no need to find the object.

    I think the easiest way to use this overall idea would be to pass in the object's transform.position to camera.WorldToViewportPoint(), and then verify that the resulting point is between (0, 0) and (1, 1).

    Note, however, that this will only be true if the center of the object is visible. If the center is just outside of the edge of the screen, some parts of the object might still be visible, but this method would indicate that the object is not visible. A false negative, basically. Typically, you'd rather avoid false negatives and are willing to accept a few false positives (your code thinks the object is on the screen, even if it's just barely off far enough to not even affect a single pixel), and that is commonly achieved by computing a bounding shape (usually an AABB or sphere) that is big enough to fully encapsulate your whole object and comparing it to the camera's frustum planes. GeometryUtility can help with some of that.