Unity中如何限制相机Y轴不低于玩家且避免移动卡顿
Unity鼠标控制相机防下移修复方案
问题根源
- 原有修复逻辑仅跳过了低于Y轴阈值时的相机位置更新,但
offset变量仍会持续累积鼠标输入产生的负Y轴偏移,后续需要大量上滑操作抵消已累积的负偏移才会让相机重新移动,表现为卡顿/无响应。 - 玩家位置发生变化时,若当前
offset计算后Y值低于阈值,相机会直接停止位置更新,无法跟随玩家移动。
修复代码
核心思路:计算完新偏移量后直接钳制偏移的Y值,确保相机Y轴永远不会低于玩家Y轴,全程不跳过位置更新步骤,保证相机跟随正常。
using System.Collections; using UnityEngine; public class CameraController : MonoBehaviour { private Vector3 offset; public Transform player; public float camPosX; public float camPosY; public float camPosZ; public float camRotationX; public float camRotationY; public float camRotationZ; public float turnSpeed; private void Start() { offset = new Vector3(player.position.x + camPosX, player.position.y + camPosY, player.position.z + camPosZ); transform.rotation = Quaternion.Euler(camRotationX, camRotationY, camRotationZ); } private void Update() { offset = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * Quaternion.AngleAxis(Input.GetAxis("Mouse Y") * turnSpeed, Vector3.right) * offset; // 新增:钳制offset的Y值,确保偏移后的相机Y不会低于玩家Y offset.y = Mathf.Max(offset.y, 0); transform.position = player.position + offset; transform.LookAt(player.position); } }
内容的提问来源于stack exchange,提问作者Coder Gautam YT
相关产品推荐
相关产品推荐

