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

Unity相机控制异常:鼠标无法控制相机上下移动,左右行走功能正常

相机上下旋转失效问题修复

你的代码有两个核心问题导致相机无法上下移动:

  1. 语法错误:parent.Rotate(Vector3., mousey)这一行里Vector3.后面缺少具体轴参数,这行代码本身无法正常运行
  2. 逻辑错误:上下旋转不该作用在parent对象上——parent应该只处理左右转向(对应行走方向),相机的上下抬头/低头需要单独控制相机自身的旋转

下面是修正后的完整代码,同时添加了角度限制避免相机翻转:

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

public class CameraControl : MonoBehaviour
{
    [SerializeField] float mouseSensitivity = 100f;
    [SerializeField] float maxLookAngle = 85f; // 限制上下旋转的最大角度,防止过度翻转

    private Transform parent;
    Vector2 turn;

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

    void Update()
    {
        Rotate();
    }

    void Rotate()
    {
        // 鼠标X轴控制玩家(parent)绕Y轴旋转,实现左右行走转向
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        parent.Rotate(Vector3.up, mouseX);

        // 鼠标Y轴控制相机自身绕X轴旋转,实现上下抬头低头
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
        turn.y += mouseY;
        // 把上下旋转角度限制在合理范围,避免相机360度翻转
        turn.y = Mathf.Clamp(turn.y, -maxLookAngle, maxLookAngle);
        // 将计算好的角度应用到相机的局部旋转上
        transform.localRotation = Quaternion.Euler(-turn.y, 0, 0);
    }
}

关键修改说明:

  • 移除了无效的错误代码行,将上下旋转的操作对象从parent改为相机自身的transform
  • 添加了maxLookAngle参数,通过Mathf.Clamp限制上下旋转的角度,避免相机翻转到不合理的姿态
  • 分离了玩家转向和相机视角控制的逻辑,确保左右控制行走、上下控制视角的功能独立生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:17:01