Manual boundaries

Taking boundaries automatically from CameraViewport is a good solution, but it will not work as you would expected if run it in other Aspect Ratio.
I think, it would be easier just expose two Vector2-s for bottom-left and top-right corners and put some values manually:

  private Vector2 _boundariesBottomLeft, _boundariesTopRight;
    newPos.x = Mathf.Clamp(transform.position.x + delta.x, _boundariesBottomLeft.x, _boundariesTopRight.x);
    newPos.y = Mathf.Clamp(transform.position.y + delta.y, _boundariesBottomLeft.y, _boundariesTopRight.y);

1 Like

Great analysis. Have you tested out what you think will work?

sure, it works on any aspect-ratio (wider then 9:16), my screenshot is from Unity-Game-View with aspect ratio 16:9 (1920:1080)
You can also add some Gizmos to see it better:

  void OnDrawGizmos() {
    Debug.DrawRay(_boundariesBottomLeft, Vector2.up, Color.yellow);
    Debug.DrawRay(_boundariesBottomLeft, Vector2.right, Color.yellow);
    Debug.DrawRay(_boundariesTopRight, Vector2.down, Color.yellow);
    Debug.DrawRay(_boundariesTopRight, Vector2.left, Color.yellow);

Privacy & Terms