Search code examples
c#unity-game-enginecamerazooming

Unity camera zoom for specific object (2D)


I would like to zoom forward and backward on specific elements only in 2D.

  • I have an orthographic camera.
  • I have a canvas containing UI elements that must not change size or
    position.

  • I also have some elements in this canvas that must be zoomed in or
    out.

An image is worth 1000 words: http://prntscr.com/ljjp8i

I want to zoom on the background (which is an image) and the cercles on it, but not on buttons/text arround the game view.

I already made some test with the following code:

   void Update()
    {
        if (Input.GetAxis("Mouse ScrollWheel") < 0) // back
        {
            Debug.Log("zoom out");
            cam.orthographicSize +=1;

        }
        if (Input.GetAxis("Mouse ScrollWheel") > 0) // forward
        {
            Debug.Log("zoom in");
        }
    }
}

Unfortunately, it does not do anything. Even though the DEbug.Log comes in, there is no change in the view. Moreover, I have no idea how it would react on all the UI elements, how to exclude elements that must not be "zoomed".

Is someone able to point me out a good resource that explains how to achieve this, or to give me guidelines soe that I can explore on my own? (Or even give the solution if you are up to ^^)

Thanks.


Solution

  • By default, the canvas is set to render in Screen Space.

    You should consider creating a separate canvas for the objects that you want to scale. Set the render mode of that canvas to World Space, and it should be affected by the orthographic size of the camera.

    enter image description here