Unity自定义FPS控制器暂停菜单相机旋转锁定失效求助
自定义FPS控制器暂停时无法锁定相机旋转的修复方案
我知道这个问题被多次提及,但我的情况略有不同:使用自行实现的FPS控制器,进入暂停菜单时无法锁定相机旋转,查阅所有类似问题的解决方案后均未解决,且因控制器挂载了大量附加组件不想替换,现附上相关脚本,怀疑问题与Time.timeScale、deltaTime有关。
问题根源
你的自定义FPS控制器中,Update和LateUpdate里的鼠标旋转逻辑(Input.GetAxis("Mouse X")/Input.GetAxis("Mouse Y"))不受Time.timeScale影响——即使你把Time.timeScale设为0,Unity仍然会每帧执行Update和LateUpdate,且鼠标输入会被正常读取,导致相机继续旋转。同时,玩家脚本没有判断暂停状态,所以旋转逻辑会一直运行。
修复方案
在玩家控制器的输入处理逻辑前,添加暂停状态判断,直接跳过所有玩家输入相关代码:
修改后的PlayerController脚本关键部分
// Update is called once per frame void Update(){ // 暂停时直接跳过所有玩家输入与移动逻辑 if (PauseMenu.paused) return; // Horizontal rotation transform.Rotate(Vector3.up * Input.GetAxis("Mouse X") * 2f); newVelocity = Vector3.up * rb.velocity.y; float speed = Input.GetKey(KeyCode.LeftShift) ? runSpeed : walkSpeed; newVelocity.x = Input.GetAxis("Horizontal") * speed; newVelocity.z = Input.GetAxis("Vertical") * speed; if (isGrounded) { if (Input.GetKeyDown(KeyCode.Space) && !isJumping) { newVelocity.y = jumpSpeed; isJumping = true; } } rb.velocity = transform.TransformDirection(newVelocity); } void LateUpdate(){ // 暂停时跳过垂直旋转逻辑 if (PauseMenu.paused) return; //Vertical rotation Vector3 e = head.eulerAngles; e.x -= Input.GetAxis("Mouse Y") *2f; e.x = RestrictAngle(e.x, -85f, 85f); head.eulerAngles = e; }
补充说明
- 利用
PauseMenu中的静态变量paused直接判断状态,无需额外定义变量,确保状态同步。 - 暂停菜单中设置的
Cursor.lockState会正常生效,暂停时光标解锁,恢复时锁定,配合上述逻辑彻底阻止相机旋转。 Input.GetAxis系列方法基于真实时间更新,和Time.timeScale无关,所以必须显式通过状态判断来禁用输入逻辑,而不能依赖Time.timeScale = 0来停止输入处理。
内容的提问来源于stack exchange,提问作者Jack Doole
相关产品推荐
相关产品推荐

