RT2010
RT2010

Reputation: 81

Why can't I zoom my Unity2D Orthographic game?

I've watched several videos and read posts that indicate I should be able to zoom the camera view during my game by changing the Size parameter for the MainCamera (Unity 2D game, orthographic projection). Doing so zooms the Scene View in and out, but nothing I change anywhere in the Inspector changes the Game view.

Can anyone advise? Thanks.

enter image description here

Upvotes: 3

Views: 2164

Answers (1)

Lorenzo Goldoni
Lorenzo Goldoni

Reputation: 585

The orthographic size defines the viewing volume of the camera and it will only zoom on the elements rendered by it. It looks like you are trying to zoom on a Canvas, but UI elements are rendered on top of the whole scene.

In order to zoom in and out you can either:

  1. set the Canvas Render Mode to World Space and then place it in front of the camera
  2. use a script that lets you zoom in on a canvas, have a look here: Pinch zoom on UI

     public class PinchZoom : MonoBehaviour
     {
         public Canvas canvas; // The canvas
         public float zoomSpeed = 0.5f;        // The rate of change of the canvas scale factor
    
         void Update()
         {
             // If there are two touches on the device...
             if (Input.touchCount == 2)
             {
                 // Store both touches.
                 Touch touchZero = Input.GetTouch(0);
                 Touch touchOne = Input.GetTouch(1);
    
                 // Find the position in the previous frame of each touch.
                 Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
                 Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
    
                 // Find the magnitude of the vector (the distance) between the touches in each frame.
                 float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
                 float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
    
                 // Find the difference in the distances between each frame.
                 float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;
    
                 // ... change the canvas size based on the change in distance between the touches.
                 canvas.scaleFactor -= deltaMagnitudeDiff * zoomSpeed;
    
                 // Make sure the canvas size never drops below 0.1
                 canvas.scaleFactor = Mathf.Max(canvas.scaleFactor, 0.1f);
             }
         }
     }
    

I hope this will help you!

Upvotes: 2

Related Questions