如何使用Unity新输入系统通过鼠标输入旋转虚拟相机?
第三人称相机全轴旋转实现(Unity新输入系统 + Character Controller)
1. 配置输入绑定
- 在Project窗口右键 →
Input Actions创建新的输入动作集(命名比如PlayerControls) - 打开动作集编辑器,添加
CameraControl动作映射,再创建两个动作:LookHorizontal:绑定到Mouse → X Axis,响应类型设为ValueLookVertical:绑定到Mouse → Y Axis,响应类型设为Value
2. 编写相机控制脚本
创建C#脚本ThirdPersonCamera,挂载到相机对象上,代码如下:
using UnityEngine; using UnityEngine.InputSystem; public class ThirdPersonCamera : MonoBehaviour { [Header("目标与参数")] public Transform target; // 绑定Character Controller的Transform public float rotationSpeed = 200f; public Vector2 verticalRotationLimit = new Vector2(-70f, 80f); // 限制垂直旋转角度,避免翻转 private InputAction _lookHorizontal; private InputAction _lookVertical; private float _currentVerticalRotation = 0f; private void Awake() { // 实例化输入动作集(替换成你创建的Input Actions类名) var playerInput = new PlayerControls(); _lookHorizontal = playerInput.CameraControl.LookHorizontal; _lookVertical = playerInput.CameraControl.LookVertical; } private void OnEnable() { _lookHorizontal.Enable(); _lookVertical.Enable(); // 锁定光标,避免拖动时乱跑 Cursor.lockState = CursorLockMode.Locked; } private void OnDisable() { _lookHorizontal.Disable(); _lookVertical.Disable(); Cursor.lockState = CursorLockMode.None; } private void Update() { // 获取鼠标输入值 float mouseX = _lookHorizontal.ReadValue<float>() * rotationSpeed * Time.deltaTime; float mouseY = _lookVertical.ReadValue<float>() * rotationSpeed * Time.deltaTime; // 处理垂直旋转(相机绕X轴) _currentVerticalRotation -= mouseY; _currentVerticalRotation = Mathf.Clamp(_currentVerticalRotation, verticalRotationLimit.x, verticalRotationLimit.y); transform.localRotation = Quaternion.Euler(_currentVerticalRotation, 0f, 0f); // 处理水平旋转(角色绕Y轴,相机跟随) target.Rotate(Vector3.up * mouseX); // 可选:添加Z轴旋转(特殊需求时开启) // float mouseZ = Input.GetAxis("Mouse ScrollWheel") * rotationSpeed * Time.deltaTime; // transform.Rotate(Vector3.forward * mouseZ); } private void LateUpdate() { // 保持相机始终在目标后方(可根据需求调整位置) transform.position = target.position + target.TransformDirection(new Vector3(0, 1.5f, -5f)); } }
3. 脚本设置与注意事项
- 将角色的Character Controller组件的Transform拖到脚本的
target字段 - 调整
rotationSpeed和verticalRotationLimit参数适配你的游戏 - 如果需要相机绕Z轴旋转,取消代码中Z轴旋转的注释,可绑定鼠标滚轮或额外按键
内容的提问来源于stack exchange,提问作者Emre
相关产品推荐
相关产品推荐

