2
\$\begingroup\$

I'd like to recycle objects as they pass behind the camera frustum -- i.e, the plane of the local Z axis, orthogonal to the camera vector: Camera.main.transform.forward.

Is there a nice method to test for the above case? That is, "if a GameObject's location < local Z = 0 plane", we can know that it is behind the camera.

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

You could use the methods in MonoBehaviour, OnBecameVisible () and OnBecameInvisible (), they are called whenever a gameObject becomes invisible or visible to the game camera.

For example:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ExampleScript : MonoBehaviour {
    void OnBecameInvisible () {
        GetComponent <Renderer> ().enabled = false;
    }

    void OnBecameVisible () {
        GetComponent <Renderer> ().enabled = true;
    }
}

I also think the cameras in Unity already cull objects by default automatically, you might not even need to do this at all.

\$\endgroup\$
0
\$\begingroup\$

You can also do it like this:

bool IsBehind(Vector3 worldPosition, Transform observer) {
    return Vector3.Dot(worldPosition - observer.position, observer.forward) < 0f;
}

This dot product computes the signed distance of the provided world position along the observer's forward axis. If it's negative, the position is behind the observer.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.