随笔之鼠标移动摄像机的方法

qq6322

1 回复12 浏览

来自课程:Steam模拟经营游戏《冒险村的商人日记》从开发到上架全流程

鼠标控制镜头移动与缩放

    public class CameraMove : MonoBehaviour
    {
        [Tooltip("默认0.15f")]
        [Range(0, 1)]
        public float scaleSmooth = 0.15f;
        public float scaleSize = 1.5f;
        public float orthographicSizeMin = 3;
        public float orthographicSizeMax = 10;

        private Camera mainCamera;
        private Vector3 tapMousePos;
        private Vector3 curMousePos;
        private bool isOutScreen = false;
        private float targetOrthographicSize;
        private float orthographicSizeDefault;


        // Start is called before the first frame update
        void Start()
        {
            mainCamera = Camera.main;
            targetOrthographicSize = mainCamera.orthographicSize;
            orthographicSizeDefault = targetOrthographicSize;
        }

        // Update is called once per frame
        void Update()
        {
            ScreenSizeChange();
            ScreenMoveChange();
        }

        private void ScreenSizeChange()
        {
            var tempSize = mainCamera.orthographicSize;
            if (Input.GetAxis("Mouse ScrollWheel") < 0)
            {
                if (mainCamera.orthographicSize <= orthographicSizeMax)
                {
                    targetOrthographicSize += scaleSize;
                }
            }
            if (Input.GetAxis("Mouse ScrollWheel") > 0)
            {
                if (targetOrthographicSize > orthographicSizeMin)
                {
                    targetOrthographicSize -= scaleSize;
                }
            }
            targetOrthographicSize = Mathf.Clamp(targetOrthographicSize, orthographicSizeMin, orthographicSizeMax);
            if (Mathf.Abs(targetOrthographicSize - tempSize) > 0.1f)
                mainCamera.orthographicSize = Mathf.Lerp(tempSize, targetOrthographicSize, scaleSmooth);
            else
                mainCamera.orthographicSize = targetOrthographicSize;
        }

        private void ScreenMoveChange()
        {
            var mousePos = Input.mousePosition;
            if (mousePos.x > Screen.width || mousePos.x < 0 ||
                mousePos.y > Screen.height || mousePos.y < 0)
            {
                isOutScreen = true;
            }
            else
            {
                if (isOutScreen)
                {
                    isOutScreen = false;
                    curMousePos = MousePositionSToW();
                }
            }
            if (Input.GetMouseButton(0))
            {
                tapMousePos = MousePositionSToW();
                mainCamera.transform.position += curMousePos - tapMousePos;
            }
            curMousePos = MousePositionSToW();
        }


        private Vector3 MousePositionSToW()
        {
            return mainCamera.ScreenToWorldPoint(Input.mousePosition);
        }
    }

全部回复(1)

发表回复

登录后可以回复