26 Jun 2015

Bounding Player to Screen

http://www.raywenderlich.com/70344/unity-2d-tutorial-physics-and-screen-sizes

http://www.aeonphyxius.com/2013/03/how-to-force-an-object-to-stay-in-the-visible-camera-area-in-unity/


My code:

/// <summary>
/// Restrict the player to the camera's boundaries
/// </summary>
private void LimitPlayerToCamera ()
{
_playerPos.x = Mathf.Clamp ( transform.position.x ,
CameraBehaviour.instance.transform.position.x - _widthOrtho + _playerBoundSize.x ,
CameraBehaviour.instance.transform.position.x + _widthOrtho - _playerBoundSize.x );

_playerPos.y = Mathf.Clamp ( transform.position.y ,
CameraBehaviour.instance.transform.position.y - Camera.main.orthographicSize + _playerBoundSize.y ,
CameraBehaviour.instance.transform.position.y + Camera.main.orthographicSize - _playerBoundSize.y );

transform.position = _playerPos;
}