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

Unity中如何限制相机Y轴不低于玩家且避免移动卡顿

Unity鼠标控制相机防下移修复方案

问题根源

  • 原有修复逻辑仅跳过了低于Y轴阈值时的相机位置更新,但offset变量仍会持续累积鼠标输入产生的负Y轴偏移,后续需要大量上滑操作抵消已累积的负偏移才会让相机重新移动,表现为卡顿/无响应。
  • 玩家位置发生变化时,若当前offset计算后Y值低于阈值,相机会直接停止位置更新,无法跟随玩家移动。

修复代码

核心思路:计算完新偏移量后直接钳制偏移的Y值,确保相机Y轴永远不会低于玩家Y轴,全程不跳过位置更新步骤,保证相机跟随正常。

using System.Collections;
using UnityEngine;

public class CameraController : MonoBehaviour
{
    private Vector3 offset;

    public Transform player;

    public float camPosX;
    public float camPosY;
    public float camPosZ;

    public float camRotationX;
    public float camRotationY;
    public float camRotationZ;

    public float turnSpeed;

    private void Start()
    {
        offset = new Vector3(player.position.x + camPosX, player.position.y + camPosY, player.position.z + camPosZ);
        transform.rotation = Quaternion.Euler(camRotationX, camRotationY, camRotationZ);
    }

    private void Update()
    {
        offset = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * Quaternion.AngleAxis(Input.GetAxis("Mouse Y") * turnSpeed, Vector3.right) * offset;
        // 新增:钳制offset的Y值,确保偏移后的相机Y不会低于玩家Y
        offset.y = Mathf.Max(offset.y, 0);
        transform.position = player.position + offset;
        transform.LookAt(player.position);
    }
}

内容的提问来源于stack exchange,提问作者Coder Gautam YT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:15:02