Search Unity

Enable camera player follow, but only when player is within 25% of game viewport.

Discussion in 'Scripting' started by wyattbiker, Dec 11, 2018.

  1. wyattbiker

    wyattbiker

    Joined:
    Sep 4, 2014
    Posts:
    18
    Attached is the scene with the ball in center. Objective is to move around and capture cubes.

    Currently the camera follows the player (ball), so the effect is the ball is centered in the viewport, and the board pans around.

    I would like camera to only follow the player when the player is within 10% of the viewport boundaries. I am trying to figure out the best way to do this with Unity scripts. Logically I need to get the current player XZ position and the viewport size and if the player is at 10% of the view boundary, then enable the camera follow.

    I assume I need current player viewport position and camera viewport size and compare. Any ideas the best way to do this, and which camera viewport methods?

    Code (CSharp):
    1. public class CameraController : MonoBehaviour {
    2.     public GameObject player;
    3.     private Vector3 offset;
    4.  
    5.     // Use this for initialization
    6.     void Start() {
    7.         offset = transform.position - player.transform.position;
    8.     }
    9.  
    10.     // Update is called once per frame
    11.     void LateUpdate() {
    12.         transform.position = player.transform.position + offset;
    13.     }
    14. }


    Screen Shot 2018-12-11 at 6.01.21 PM.png
     
  2. Thimble2600

    Thimble2600

    Joined:
    Nov 27, 2015
    Posts:
    165
    Perhaps you could use a clamp to prevent the screen from going too far.

    Code (CSharp):
    1.  
    2.         float positionX = Mathf.Clamp ( transform.position.x , 10.0f , 90.0f );
    3.         float positionY = Mathf.Clamp ( transform.position.y , 10.0f , 90.0f );
    4.         transform.position = new Vector3 ( positionX , positionY, -10.0f);
    You'll need to test to see the min (10.0f) and max (90.0f) bounds for the camera.