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

Unity相机无法沿Y轴水平旋转?自定义移动脚本故障求助

Unity相机水平旋转问题修复

你的脚本存在几个关键错误,导致水平旋转失效:

  • 两次重复设置transform.localRotation,后一次赋值直接覆盖了前一次的相机俯仰设置,同时错误地把水平轴输入用到了相机X轴旋转上
  • 玩家水平旋转第一次错误使用mouseY作为参数,还重复调用了player.Rotate
  • yRotation逻辑完全错误,没有累加旋转量,反而错误作用在相机X轴上

修正后的代码如下:

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

public class looking : MonoBehaviour
{
    [SerializeField] private float mouseSensitivity = 100f;
    [SerializeField] private Transform player;
    private float xRotation = 0f;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

        // 处理相机上下俯仰(X轴旋转)
        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);
        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);

        // 处理玩家水平旋转(Y轴旋转)
        player.Rotate(Vector3.up * mouseX);
    }
}

关键说明:

  • 相机仅负责上下视角俯仰,通过累加mouseY更新xRotation,并限制在-90到90度避免过度翻转
  • 水平旋转直接通过player.Rotate绕Y轴应用mouseX输入,无需额外yRotation变量
  • 移除了重复的旋转赋值和调用,确保逻辑清晰无冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 08:12:33