【Unity】Camera zoom function implementation

Implement mouse wheel and finger zoom

     public float zoomSpeed = 4;
     public float minZoom = 50f;
     public float maxZoom = 70f;
     private bool isCanZoom=false;
     private bool isOnScaleView = false;	


		//判断是否是移动设备
        bool IsMobilePlatform()
        {
    
    
            return Application.isMobilePlatform;
        }

	void Update()
        {
    
    
            if (!isCanZoom)
            {
    
    
                if (IsMobilePlatform)
                {
    
    
                    HandleMobileZoom();
                }
                else
                {
    
    
                    HandlePCZoom();
                }
            }
        }


      
void HandleMobileZoom()
{
    
    
    if (Input.touchCount == 2)
    {
    
    
        isOnScaleView = true;
        Touch touchZero = Input.GetTouch(0);
        Touch touchOne = Input.GetTouch(1);

        // 计算前一帧触摸的距离和当前帧触摸的距离
        float prevTouchDeltaMag = (touchZero.position - touchZero.deltaPosition - (touchOne.position - touchOne.deltaPosition)).magnitude;
        float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;

        // 计算触摸距离的变化量
        float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;

        // 根据变化量调整相机的视野(缩放)
        mainCamera.fieldOfView += deltaMagnitudeDiff * zoomSpeed * Time.deltaTime;

        // 限制相机视野的范围在 minZoom 和 maxZoom 之间
        mainCamera.fieldOfView = Mathf.Clamp(mainCamera.fieldOfView, minZoom, maxZoom);
    }
    else if (Input.touchCount <= 1) // 修改条件为小于等于 1
    {
    
    
        if (isOnScaleView)
        {
    
    
            isOnScaleView = false;
            // 在缩放结束时执行操作
        }
    }
}
		
	
		//使用滚轮进行缩放
        void HandlePCZoom()
        {
    
    
            float scrollWheel = Input.GetAxis("Mouse ScrollWheel");

            if (scrollWheel != 0f)
            {
    
    
                mainCamera.fieldOfView += -scrollWheel * zoomSpeed;
                mainCamera.fieldOfView = Mathf.Clamp(mainCamera.fieldOfView, minZoom, maxZoom);
                GameSceneMgr.Instance.PlayerController.PlayerFsmData.IsOnChangeView = true;
            }
           
        }

Guess you like

Origin blog.csdn.net/Xz616/article/details/135445391