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

Unity第三人称相机俯仰角度限制:解决90度时水平翻转问题

解决第三人称相机俯仰翻转问题

你的相机出现画面翻转的核心原因是:当俯仰角度接近90度时,相机朝向会越过“头顶/脚底”的临界线,触发LookAt逻辑中相机Up轴的方向翻转,最终导致画面旋转180度。解决的关键是严格将俯仰角度限制在90度以内,避免触发临界状态。

修改方案

  1. 限制俯仰角度的最大值为89度(绝对不能等于或超过90度)
  2. 通过代码强制锁定角度范围,防止输入或其他逻辑突破限制

修改后的完整代码

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

public class Camera : MonoBehaviour
{
    public Transform target;
    public float targetY;

    // 直接设置默认值为89,避免Inspector误设过大数值
    [SerializeField] private float xRotMax = 89f;
    public float rotSpeed;
    public float scrollSpeed;

    public float distance;
    public float minDistance;
    public float maxDistance;

    private float xRot;
    private float yRot;
    private Vector3 targetPos;
    private Vector3 dir;

    private void Update()
    {
        xRot += Input.GetAxis("Mouse Y") * rotSpeed * Time.deltaTime;
        yRot += Input.GetAxis("Mouse X") * rotSpeed * Time.deltaTime;
        distance += -Input.GetAxis("Mouse ScrollWheel") * scrollSpeed * Time.deltaTime;

        // 严格锁定俯仰角度在-89到89之间,杜绝临界翻转
        xRot = Mathf.Clamp(xRot, -xRotMax, xRotMax);
        distance = Mathf.Clamp(distance, minDistance, maxDistance);

        targetPos = target.position + Vector3.up * targetY;

        dir = Quaternion.Euler(-xRot, yRot, 0f) * Vector3.forward;
        transform.position = targetPos + dir * -distance;
    }

    private void LateUpdate()
    {
        transform.LookAt(targetPos);
    }
}

关键改动说明

  • 将xRotMax默认值设为89f,并通过[SerializeField]标记(可选,方便在Inspector查看同时降低误改风险)
  • 用Mathf.Clamp强制把xRot限制在[-89, 89]区间内,确保相机永远不会绕X轴旋转到90度的临界位置,从根源避免画面翻转问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 20:10:48