- Home /
Checking if player leaves the screen bounds
Since my camera never moves, I'm trying to detect when my player leaves the camera bounds. I was thinking this could be achieved by adding a collider to the left and right of the camera bounds and firing a ray from my player every update to see if they are still inside the camera bounds or not.
Then I noticed that you can get the pixel width of the camera using pixelWidth. Is there a way I could calculate without physics if my player has left on the screen on either the right or left hand side?
Answer by testure · Sep 25, 2011 at 09:49 PM
Here's what I do (roughly). Note that this code only checks the top and bottom of the screen, because in my game the player never leaves the center of the screen (horizontally). Also, I'm using a ratio because I want the player to be able to get to a certain point before the camera starts to follow him- I never want the player to completely leave the screen.. so there's a bit of an edge 'safe frame' that I'm checking.
bool SafeFrameCheck()
{
Vector3 screenPos = _cameraRef.WorldToScreenPoint(Player.Instance.xform.position);
float ratio = screenPos.y / _cameraRef.pixelHeight;
if(ratio < 0f) // if we're below our safe frame
return false;
if(ratio > .7f) // if we're above our safe frame, return false
return false;
return true; // we're inside our safe frame.
}