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

Unity中鼠标控制相机时轴切换视角重置问题求助

鼠标控制VR视角时切换轴旋转重置的解决方案

问题出在代码中每次处理单一轴旋转时,直接覆盖了transform.localRotation,没有同时应用两个轴的旋转数据。比如处理水平旋转时,只设置了绕Y轴的旋转,完全丢弃了垂直旋转的角度;处理垂直旋转时同理,导致另一轴的旋转被重置为初始状态。

解决方案

需要在更新旋转时,同时结合**yaw(水平)和pitch(垂直)**两个角度的旋转。可以通过Quaternion.Euler直接创建包含两个轴旋转的四元数,同时建议限制垂直旋转的角度,避免视角过度上下翻转。

修正后的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class MouseLook : MonoBehaviour
{
    public InputActionReference horizontalLook;
    public InputActionReference verticalLook;
    public float lookSpeed = 0.25f;
    public Transform cameraTransform;
    float pitch;
    float yaw;
    // 限制垂直旋转的范围,避免过度抬头/低头
    public float pitchMin = -80f;
    public float pitchMax = 80f;
    
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        horizontalLook.action.performed += HandleHorizontalLookChange;
        verticalLook.action.performed += HandleVerticalLookChange;
    }

    void HandleHorizontalLookChange(InputAction.CallbackContext obj)
    {
        yaw += obj.ReadValue<float>() * lookSpeed;
        // 同时应用水平和垂直旋转
        UpdateRotation();
    }

    void HandleVerticalLookChange(InputAction.CallbackContext obj)
    {
        pitch -= obj.ReadValue<float>() * lookSpeed; // 调整符号让鼠标操作方向和视角移动更匹配
        // 限制垂直旋转角度
        pitch = Mathf.Clamp(pitch, pitchMin, pitchMax);
        // 同时应用水平和垂直旋转
        UpdateRotation();
    }

    void UpdateRotation()
    {
        // 合并两个轴的旋转角度,生成最终旋转
        transform.localRotation = Quaternion.Euler(pitch, yaw, 0f);
    }
}

关键调整说明

  • 新增UpdateRotation方法统一处理旋转更新,确保每次都同时应用yaw和pitch的角度
  • 对pitch做范围限制,防止视角翻转到不合理的角度
  • 调整垂直旋转的符号,让鼠标操作方向和视角移动方向更符合直觉(可根据需求自行修改)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:55:37