Hello
How do I detect if my objects have gone off screen when using a 3D scene with a background canvas?
I cant get cubes with box colliders to work, or WillBeInvisible
Paul
Hello
How do I detect if my objects have gone off screen when using a 3D scene with a background canvas?
I cant get cubes with box colliders to work, or WillBeInvisible
Paul
Hey @thesaxtonator!
To check whether object is on screen or not you can transform the object’s position from world space to viewport space using the current camera, as below:
viewCamera.WorldToViewportPoint(worldPosition);
This will return a Vector3 containing a normalized position of the given point on viewport, relative to the camera, where the bottom-left is (0,0) and the top right is (1,1). When a value below 0 or above 1 is returned on either of the axes, the given position should be considered off-screen. The z component is being returned in the world units from the camera, so anything above 0 means that it’s in front of the camera, and anything that’s below 0 is behind. With that knowledge, you can create a simple bool to check if a given position is in camera’s view or not:
private bool IsPositionInView(Vector3 worldPosition, Camera viewCamera)
{
Vector3 viewportPosition = viewCamera.WorldToViewportPoint(worldPosition);
return viewportPosition.z > 0 &&
viewportPosition.x >= 0 && viewportPosition.x <= 1 &&
viewportPosition.y >= 0 && viewportPosition.y <= 1;
}
That will only check if a given position is in the view, not the entire object. Keep that in mind if you want to despawn objects when they go out of the camera’s frustum, as you might want to increase the range check - i.e. check if the object is above or equal to 0.5 and below or equal to 1.5, to prevent objects’ disappearing at the edges of the screen.
However, in your case (preventing objects from going off screen) this solution should work just fine.