You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity相机旋转异常:仅右键点击帧旋转,无法持续旋转

问题根源

原脚本里判断右键输入用了Input.GetMouseButtonDown(1),这个方法仅在鼠标按键按下的第一帧返回true,所以rotating变量只会在点击右键的瞬间为true,后续帧都会被设为false,导致相机只能在点击的那一帧旋转。

修正后的完整脚本
using UnityEngine;

public class CameraMovement : MonoBehaviour
{
    private Vector3 _cameraPosition;
    private float _xRotation;
    private float _yRotation;
    public float sensitivity = 100f;
    public float cameraSpeed = 5f;

    void Start()
    {
        _cameraPosition = transform.position;
        // 初始化旋转值为当前相机的欧拉角
        _yRotation = transform.eulerAngles.y;
        _xRotation = transform.eulerAngles.x;
    }

    void Update()
    {
        // 改用GetMouseButton判断右键是否按住
        bool isRotating = Input.GetMouseButton(1);

        if (isRotating)
        {
            // 获取鼠标输入,乘以灵敏度和deltaTime保证帧率无关
            float mouseX = Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime;
            float mouseY = Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime;

            // 更新旋转角度
            _yRotation += mouseX;
            _xRotation -= mouseY;
            // 限制X轴旋转范围,避免过度抬头/低头
            _xRotation = Mathf.Clamp(_xRotation, -90f, 90f);

            // 应用旋转
            transform.eulerAngles = new Vector3(_xRotation, _yRotation, 0f);
        }

        // 相机移动逻辑,改用transform.TransformDirection保证基于相机朝向移动
        Vector3 moveDir = Vector3.zero;
        if (Input.GetKey(KeyCode.W)) moveDir += Vector3.forward;
        if (Input.GetKey(KeyCode.S)) moveDir += Vector3.back;
        if (Input.GetKey(KeyCode.A)) moveDir += Vector3.left;
        if (Input.GetKey(KeyCode.D)) moveDir += Vector3.right;
        if (Input.GetKey(KeyCode.Space)) moveDir += Vector3.up;
        if (Input.GetKey(KeyCode.LeftShift)) moveDir += Vector3.down;

        // 归一化避免斜向移动速度过快,乘以deltaTime保证帧率无关
        if (moveDir.magnitude > 0)
        {
            moveDir.Normalize();
            _cameraPosition += transform.TransformDirection(moveDir) * cameraSpeed * Time.deltaTime;
            transform.position = _cameraPosition;
        }
    }
}
关键修改说明
  • 右键输入判断:把Input.GetMouseButtonDown(1)改成Input.GetMouseButton(1),后者会在右键按住的每帧都返回true,保证旋转持续生效。
  • 旋转逻辑优化:
    • 用变量存储旋转角度,避免直接修改transform.eulerAngles导致的角度异常。
    • 添加Time.deltaTime让旋转速度不受帧率影响。
    • 限制X轴旋转范围(-90°到90°),防止相机翻转。
  • 移动逻辑优化:
    • 使用transform.TransformDirection将世界空间方向转换为相机本地空间方向,保证移动是基于相机朝向的。
    • 归一化移动方向,避免斜向移动时速度过快。
    • 添加Time.deltaTime让移动速度不受帧率影响。

内容的提问来源于stack exchange,提问作者eee143

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 08:00:16