学习 Unity 手写Unity相机旋转脚本 理理 2024-10-30 2024-10-30 学三个月C#和一个月Unity后,试图边学边开发游戏,首先要解决的便是摄像机。 其实Unity是提供了名叫cinemamachine的插件的,功能强大,然而我不想用Unity提供的,想自己手写一个,于是写了一个。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 using Unity.VisualScripting; using UnityEngine; public class CameraController : MonoBehaviour { public Transform Target; [Header("设置相机看角色头顶多高位置")] public float upLook; [Header("相机竖直方向限制")] public float mYvalue; [Header("鼠标旋转灵敏度")] public float sensitivityMouseRotate = 100f; [Header("鼠标缩放灵敏度")] public float sensitivityMouse = 5f; [Header("相机和人物距离")] public float distance = 5f; private float mX = 0; // 累积X轴旋转 private float mY = 0; // 累积Y轴旋转 void LateUpdate() { Vector3 lookPosition = Target.position + Target.up * upLook; // 累积相机旋转的值 mX += Input.GetAxis("Mouse X") * sensitivityMouseRotate * Time.deltaTime; mY -= Input.GetAxis("Mouse Y") * sensitivityMouseRotate * Time.deltaTime; mY = Mathf.Clamp(mY, -mYvalue, mYvalue); // 设置相机的旋转状态 Quaternion myRotation = Quaternion.Euler(mY, mX, 0); // 设置distance值 float scroll = Input.GetAxis("Mouse ScrollWheel"); distance -= scroll * sensitivityMouse * 0.5f; distance = Mathf.Min(distance, 8f); distance = Mathf.Max(distance, 1.5f); // 更新相机的位置,使其与目标对象保持一定的距离 Vector3 position = Target.position + Vector3.up * upLook - myRotation * Vector3.forward * distance; this.transform.position = position; this.transform.rotation = myRotation; this.transform.LookAt(lookPosition); } }
这个相机的功能是,随着鼠标旋转可以围绕角色转,同时缩放鼠标滚轮可以拉近/拉远镜头。为了防止上下移动幅度过大,进行了clamp取值,整体还是不错的。