Home > Back-end >  How to add a limit to how far I can zoom-in or out in Unity
How to add a limit to how far I can zoom-in or out in Unity

Time:10-13

So i have this code for zooming in and out from my character but I wanted to put a limit on how much I wanted to zoom. Is there any way I can do that?

using UnityEngine;

public class MouseWheelZoom : MonoBehaviour
{
    [SerializeField]
    private float ScrollSpeed = 10;
    private Camera ZoomCamera;

    private void Start()
    {
        ZoomCamera = Camera.main;
    }

    void Update()
    {
        if (ZoomCamera.orthographic)
        {
            ZoomCamera.orthographicSize -= Input.GetAxis("Mouse ScrollWheel") * ScrollSpeed;
        }
        else
        {
            ZoomCamera.fieldOfView -= Input.GetAxis("Mouse ScrollWheel") * ScrollSpeed;
        }
    }
}

CodePudding user response:

Unity has the built-in function Mathf.Clamp(value, min, max). In this case, you could use it like this:

ZoomCamera.OrthographicSize = Mathf.Clamp(ZoomCamera.OrthographicSize,
                                    <min value>,
                                    <max value>);
  • Related