Detect from which side of camera object is out of screen

Hi,

First of all it’s a 2D game. How can I detect from which side of the camera the object became invisible? Currently I’m using void OnBecameInvisible() but with them I can handle only one side when the object leaves it from the left side. Of course it doesn’t work when the player moves back and the object leaves the screen from right side.

Here is the code that I’m using right now:

public float offset = 5;

void OnBecameInvisible() {
	transform.position = new Vector3(Camera.main.ViewportToWorldPoint(Vector3.one).x + offset, transform.position.y, transform.position.z);
}

I’d never heard of this function before, that’s very useful!

If it’s a 2D game, and youre only interested in the left and right sides of the screen this should work (you can modify it to do all 4 sides of the screen too, with a bit of thought about how corners are handled).

So the thing you’re asking for is basically this:

bool exitedLeft = Camera.main.transform.position.x > transform.position.x;

But I’m not totally sure what you’re trying to do. It looks like clamp the object to remain on-screen? If so you could modify like this:

     public float offset = 5;
     
     void OnBecameInvisible() {
        bool exitedLeft = Camera.main.transform.position.x > transform.position.x;
        float side = exitedLeft ? 0 : 1, sideOffset = exitedLeft ? offset : -offset;
        float posX = Camera.main.ViewportToWorldPoint(new Vector3(side, 1, 1)).x + sideOffset;
        transform.position = new Vector3(posX, transform.position.y, transform.position.z);
     }

make a box with boundary.

from a other project i had:

[System.Serializable]
public class Boundary
{
	public float xMin,xMax, zMin, zMax;
}

and the code:

		Vector3 temp = transform.position;
		if (temp.x > boudary.xMax + 0.5f) {
			temp.x = boudary.xMin -0.5f ;
		} else if (temp.x < boudary.xMin - 0.5f) {
			temp.x = boudary.xMax + 0.5f ;
		}
// at the end
transform.position = temp;

so if the object is more than 0.5 out of the x boundary it goes to the other side.
In my case the boundary where static. Just make them dynamiclly ajust to your camera and then your done.