Home > front end >  how to check if obj is out of cam unity code 2d
how to check if obj is out of cam unity code 2d

Time:04-22

This was my code

void OnBecameInvisible()
{
    Debug.Log("he yyou lef tme");
}

It should debug "he yyou lef tme"

whenever the player exits the camera range but it doesn't work

CodePudding user response:

I personally had bad experiences using the OnBecameVisible function in Unity.

There are some different ways you can go about this depending on what you want to do.

using GeometryUtility.TestPlanesAABB:

private bool I_Can_See(GameObject Object) {

          Plane[] planes = GeometryUtility.CalculateFrustumPlanes(Camera);
          if (GeometryUtility.TestPlanesAABB(planes , Object.collider.bounds))
              return true;
          else
              return false;
     }

Or

Calculate the position of your player on the screen using Camera.WorldToViewportPoint. If this is between 0 or 1 the player is visible on the screen. More info here.

Like I said I prefer the methods above, because I've always had problems with the render OnBecameVisible and isVisible functions.

CodePudding user response:

If you are using a Screen Space Canvas, you can check with this script:

using UnityEngine;

public class VisibleTest : MonoBehaviour
{
    RectTransform rect;
    Rect screenBounds = new Rect(0f, 0f, Screen.width, Screen.height);

    void Start()
    {
        rect = GetComponent<RectTransform>();
    }

    void Update()
    {
        Debug.Log(IsVisible());
    }

    public bool IsVisible()
    {
        Vector3[] corners = new Vector3[4];
        rect.GetWorldCorners(corners);

        for (var i = 0; i < corners.Length; i  )
        {
            if (screenBounds.Contains(corners[i]))
            {
                return true;
            }
        }
        return false;
    }
}
  • Related