Search Unity

Camera Boundaries

Discussion in '2D' started by SwiftyMove, Apr 27, 2016.

  1. SwiftyMove

    SwiftyMove

    Joined:
    Jul 9, 2013
    Posts:
    15
    I've tried unsuccessfully to make a script that keeps the player within the view of the camera. My game is an infinite runner type, and I only need the restriction to be for the width of the screen as it's a portrait orientated game. Any help would be greatly appreciated, thank you!
     
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    In LateUpdate you need to check if the left side of your player has passed the left side of the screen, or if the right side of your player has passed the right side of the screen. If it has, then set the player's position equal to that side's position.

    The left side of your player is (player position - player half width).
    The right side of your player is (player position + player half width).

    When your player is perfectly on the left side of the screen, his position would be:
    (cameraPosition - (screen half width + player half width)).
    When your player is perfectly on the right side, his position would be:
    (cameraPosition + (screen half width - player half width)).

    So here's the pseudocode:

    Is (player position - player half width) less than (cameraPosition- screen half width)?
    If yes, set (player position) equal to (cameraPosition - (screen half width + player half width)).
    If no, check: Is (player position + player half width) is greater than (cameraPosition+ screen half width)
    If yes, set (player position) equal to (cameraPosition+ (screen half width - player half width)).
    That is essentially one if/else statement. You would need another if/else if you want top and bottom, and you would use half-heights all around instead of width.

    You can get the World Space screen size like this:
    Code (CSharp):
    1. float height = Camera.main.orthographicSize * 2.0f;
    2. float width = height * Screen.width / Screen.height;
    Then you need to get the half-width of your player. Maybe using "SpriteRenderer.bounds.size * 0.5f" or "Collider.bounds.size * 0.5f".
     
    Last edited: Apr 28, 2016
  3. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    I forgot to include the camera position in that pseudocode math. Updated.