Search Unity

Question Checking the visibility of the object to the camera.

Discussion in 'Prefabs' started by Zimaell, Mar 2, 2023.

  1. Zimaell

    Zimaell

    Joined:
    May 7, 2020
    Posts:
    409
    I shoot a beam into the camera and check if there are any interruptions
    Code (CSharp):
    1. Vector3 direction = controller.transform.position - MainCamera.transform.position;
    2.     Debug.DrawRay(controller.transform.position, direction, Color.red); // direction bottom
    3.     if(Physics.Raycast(controller.transform.position, direction, out hit)){
    4.         Debug.Log(hit.collider); // hit to terrain
    5.         }
    but the beam visually goes down and not towards the camera, tell me what's wrong?
     
  2. SF_FrankvHoof

    SF_FrankvHoof

    Joined:
    Apr 1, 2022
    Posts:
    780
    This is a vector FROM the Camera TO the controller.
    You want the opposite:

    MainCamera.transform.position - controller.transform.position
     
    Zimaell likes this.
  3. Zimaell

    Zimaell

    Joined:
    May 7, 2020
    Posts:
    409
    exactly, meh.
    instead of prompt as it is better to check all object instead of a point?
    I think to launch 4 rays from extreme points (bottom left / right, top left / right), then maybe there is a more reliable way?
     
  4. SF_FrankvHoof

    SF_FrankvHoof

    Joined:
    Apr 1, 2022
    Posts:
    780
    Does your object have a renderer?
    Unity - Scripting API: MonoBehaviour.OnBecameVisible() (unity3d.com)

    Edit: Nvm, that doesn't take occlusion into account.

    Launching rays from Bounds would probably be your best bet.
     
    Zimaell likes this.
  5. Zimaell

    Zimaell

    Joined:
    May 7, 2020
    Posts:
    409
    I need to know the distance too...
    I just thought I could use spherecast, but they write there that there are a lot of problems and inaccuracies with it
    so I will let 4 rays ...