如何限制Unity相机Y轴旋转并实现玩家朝向移动方向?
问题1 相机俯仰角限制修复
失效原因
直接操作transform.eulerAngles时,Unity会自动将角度归一化到0~360范围,直接对该值做Mathf.Clamp会出现跳变,无法达到限制效果。
修复步骤
- 新增两个配置参数和一个私有存储变量,用于控制俯仰角范围
[Header("相机设置")] [Range(-89f, 0f)] public float minPitchAngle = -60f; [Range(0f, 89f)] public float maxPitchAngle = 60f; private float _currentPitch = 0f;
- 修改
CameraController方法的俯仰计算逻辑,先对私有变量做累加和限制,再赋值给欧拉角
public void CameraController() { RelativeVector = transform.InverseTransformPoint(FocusPoint.transform.position); RelativeVector /= RelativeVector.magnitude; TurnDiraction = (RelativeVector.x / RelativeVector.magnitude); // 替换原来的俯仰赋值逻辑 _currentPitch -= touchField.TouchDist.y * Sensivility * Time.deltaTime; _currentPitch = Mathf.Clamp(_currentPitch, minPitchAngle, maxPitchAngle); FocusPoint.transform.localEulerAngles = new Vector3(_currentPitch, 0, 0); FocusPoint.transform.parent.Rotate(transform.up * touchField.TouchDist.x * Sensivility * Time.deltaTime); }
问题2 玩家朝向移动方向实现
逻辑调整
原有逻辑仅在摇杆纵向输入大于0时触发转向,且绑定相机焦点参数,适配性差。直接基于摇杆输入的移动方向计算目标朝向即可:
public void Movment() { if (characterController.isGrounded && gravityVector.y < 0) { gravityVector.y = -2; } gravityVector.y += gravityPower * Time.deltaTime; characterController.Move(gravityVector * Time.deltaTime); if (characterController.isGrounded) { motionVector = transform.right * joystick.Horizontal + transform.forward * joystick.Vertical; characterController.Move(motionVector * PlayerSpeed * Time.deltaTime); // 替换原有转向逻辑 if (motionVector.magnitude > 0.1f) { Quaternion targetRotation = Quaternion.LookRotation(new Vector3(motionVector.x, 0, motionVector.z)); transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, 800 * Time.deltaTime); // 同步修正相机父节点旋转,避免转向时相机跟着偏移 FocusPoint.transform.parent.rotation = Quaternion.RotateTowards(FocusPoint.transform.parent.rotation, targetRotation, 800 * Time.deltaTime); } } }
注意事项
- 俯仰角限制范围不要设置到±90度,避免触发万向锁问题
- 转向速度800可单独提取为公共参数,根据需求调整
- 确保相机父节点仅做水平旋转,FocusPoint仅做上下俯仰,层级关系不要修改
内容的提问来源于stack exchange,提问作者Tou Fix
相关产品推荐
相关产品推荐

