- Home /
Problem is "renderer.isVisible"
Hi,
To determine when my objects are out of screen for screen wrapping I use "renderer.isVisible" but it returns true if the object is visible in the editor panel and out of screen in game panel and it makes it cumbersome to test the game in the editor.
Is there anyway to overcome this? Perhaps by using a better approach to determine if an object is out of screen in a 2D game with orthographic camera.
Thanks.
Answer by UnbreakableOne · Aug 19, 2015 at 12:42 PM
Solution I came up with was to calculate bounds of the screen in world space and check if a game object is inside those.
In Awake() or something:
screenBottomLeft = cam.ViewportToWorldPoint(new Vector3(0, 0, transform.position.z));
screenTopRight = cam.ViewportToWorldPoint(new Vector3(1, 1, transform.position.z));
screenBottomRight = cam.ViewportToWorldPoint(new Vector3(1, 0, transform.position.z));
screenTopLeft = cam.ViewportToWorldPoint(new Vector3(0, 1, transform.position.z));
and then:
bool amIVisible()
{
if (transform.position.x > screenTopRight.x || transform.position.x < screenTopLeft.x)
{
return false;
}
if (transform.position.y > screenTopRight.y || transform.position.y < screenBottomRight.y)
{
return false;
}
return true;
}
Answer by Ekta-Mehta-D · Aug 18, 2015 at 12:07 PM
Hii..
Look at this :
Check Object is out of the camera view
Use this function and Attach this script to object and make operation you want.
void OnBecameInvisible() {
//do something here
}
This may work for you . Thanks.
Answer by brunopava · Aug 18, 2015 at 12:13 PM
I have a script that can be aplied to this.
private float _clampingAngle = 90f;
public bool isVisible = false;
private Camera _mainCamera;
private Transform _itSelf;
private Transform _cameraTransform;
private void Awake()
{
_mainCamera = Camera.main;
_cameraTransform = _mainCamera.transform;
_itSelf = transform;
}
private void Update()
{
if (Vector3.Angle (_itSelf.position - _cameraTransform.position, _cameraTransform.forward) > _clampingAngle)
return;
Vector2 screenPosition = _mainCamera.WorldToViewportPoint(_itSelf.position);
if(screenPosition.x >= 0 && screenPosition.x <=1 && screenPosition.y >=0 && screenPosition.y <=1)
{
isVisible = true;
}
else
{
isVisible = false;
}
}