I write a script that can rotate and zoom in the camera

  1. I think the fixed cinemachine camera is not that awesome to me, so I write this script to rotate the camera, then we can look around. I am just a noob and there might cause some bugs…But so far it works fine to me.
using Cinemachine;
using UnityEngine;

[RequireComponent(typeof(CinemachineVirtualCamera))]
namespace RPG.Core
{
    public class FollowCamera : MonoBehaviour
    {
        [SerializeField] private float _rotationPowerHori = 10f;
        [SerializeField] private float _rotationPowerVert = 10f;
        [SerializeField] private float _rotationPower = 15f;
        [SerializeField] private float _zoomFactor = 10f;
        private CinemachineVirtualCamera _cm;

        private void Start()
        {
            _cm = GetComponent<CinemachineVirtualCamera>();
        }

        private void Update()
        {
            if (Input.GetMouseButton(1))
            {
                RotateCamera();
                ZoomCamera();
            }
            else
            {
                Cursor.visible = true;
                Cursor.lockState = CursorLockMode.None;
            }
        }

        /// <summary>
        /// Control Rotation
        /// </summary>
        private void RotateCamera()
        {
            Cursor.visible = false;
            Cursor.lockState = CursorLockMode.Confined;

            #region Control Horizontal Rotation

            var lookX = Input.GetAxis("Mouse X");

            var nextYRotation =
                transform.rotation * Quaternion.AngleAxis(lookX * _rotationPowerHori, Vector3.up);

            #endregion Control Horizontal Rotation

            #region Control Vertical Rotation


            var lookY = Input.GetAxis("Mouse Y");

            var nextXRotation =
                transform.rotation * Quaternion.AngleAxis(lookY * _rotationPowerVert, -Vector3.right);

            // clamp the angle
            var xAngle = nextXRotation.eulerAngles.x;

            xAngle = Mathf.Clamp(xAngle, 10, 60);

            #endregion Control Vertical Rotation


            var nextRotation =
                Quaternion.Euler(xAngle, nextYRotation.eulerAngles.y, 0);
            transform.rotation = Quaternion.Lerp(transform.rotation, nextRotation, Time.deltaTime * _rotationPower);
        }

        private void ZoomCamera()
        {
            var zoomIn = -Input.GetAxis("Mouse ScrollWheel");
            // get the camera distance
            var fov = _cm.GetCinemachineComponent<CinemachineFramingTransposer>().m_CameraDistance;
            fov += zoomIn * _zoomFactor;
            fov = Mathf.Clamp(fov, 2, 12);
            _cm.GetCinemachineComponent<CinemachineFramingTransposer>().m_CameraDistance = fov;
        }
    }
}
  1. add a empty game object call FollowTarget to the player
  2. add the script to cinemachine
  3. let the cinemachine follow the FollowTarget that metioned below.
    Game 01
1 Like

Well done!

Thx!

Privacy & Terms