Employed Camera Zooming in the Virtual Camera

This might be hacky but I’m pretty stoked that I was able to get it working… even though it seems pretty easy.
Wanted to use the player controller but couldnt find mouse scroll in the options so just did it this way…
( I put an ortho size boundary of between 3 and 7 as you will see)

using UnityEngine;
using Cinemachine;

public class CameraZoom : MonoBehaviour
{
    [SerializeField] CinemachineVirtualCamera virtualCamera;
    float cameraDistance;
    [SerializeField] float sensitivity = 10f;

    void Update()
    {
        if (Input.GetAxis("Mouse ScrollWheel") != 0)
        {
            cameraDistance += Input.GetAxis("Mouse ScrollWheel") * sensitivity;

            cameraDistance = cameraDistance < 3 ? 3 : cameraDistance;
            cameraDistance = cameraDistance > 7 ? 7 : cameraDistance;

            virtualCamera.m_Lens.OrthographicSize = cameraDistance;
        }
    }
}
1 Like

I loved your zoom code!

I added Mathf.Lerp to it to make it smooth!

using UnityEngine;
using Cinemachine;
using UnityEngine.Rendering;

public class CameraZoom : MonoBehaviour
{
    [SerializeField] CinemachineVirtualCamera virtualCamera;
    [SerializeField] float sensitivity = 10f;

    [SerializeField] private float maxZoom = 3f;
    [SerializeField] private float minZoom = 10f;
    [SerializeField] private float zoomSpeed = 5f;

    private float startingZoom;
    private float targetZoom;
    private float currentZoom;

    private void Start() 
    {
        startingZoom = targetZoom = currentZoom = virtualCamera.m_Lens.OrthographicSize;
    }

    void Update()
    {
        if (Input.GetAxis("Mouse ScrollWheel") != 0)
        {
            targetZoom += Input.GetAxis("Mouse ScrollWheel") * -sensitivity;

            targetZoom = Mathf.Clamp(targetZoom, maxZoom, minZoom);
        }
        
        currentZoom = Mathf.Lerp(currentZoom, targetZoom, Time.deltaTime * zoomSpeed);
        virtualCamera.m_Lens.OrthographicSize = currentZoom;
    }
}

It’s worth noting that maxZoom is the smaller number here because the “zoom” is actually just the orthographic size and a smaller orthographic size means more zoom.

As a side note, it appears that the virtual camera obeys the bounding shape of its starting size, and doesn’t readjust when you zoom in or out - if anyone can figure out that one, it’d be very nice.

1 Like

Privacy & Terms