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

Unity点击拖拽相机功能修改:将XY轴移动改为XZ轴移动求助

修复方案

问题根源

  • 原代码将鼠标Y轴输入赋值给了相机Y轴坐标,导致移动在XY平面生效,而非你需要的XZ平面
  • transform.Translate默认使用相机局部坐标系,若你的相机是俯视角倾斜朝向地面,局部坐标系的Z轴会斜向地面,直接赋值仍会导致相机高度异常变化

修复后代码

using UnityEngine;

public class CameraDragMove : MonoBehaviour
{
    public float panSpeed = 10f;
    // 如果你需要限制相机移动范围,可以加上XZ轴的上下限参数
    // public Vector2 xLimit;
    // public Vector2 zLimit;

    void Update()
    {
        // 注:Input.GetMouseButton(0)对应鼠标左键,右键对应参数为1
        if (Input.GetMouseButton(0)) 
        {
            var newPosition = new Vector3();
            newPosition.x = Input.GetAxis("Mouse X") * panSpeed * Time.deltaTime;
            // 将鼠标Y轴输入赋值给Z轴,实现XZ平面移动
            newPosition.z = Input.GetAxis("Mouse Y") * panSpeed * Time.deltaTime;
            // 第二个参数指定Space.World,使用世界坐标系移动避免倾斜相机的高度偏移
            transform.Translate(-newPosition, Space.World);

            // 如果需要限制移动范围,放开以下注释即可
            // transform.position = new Vector3(
            //     Mathf.Clamp(transform.position.x, xLimit.x, xLimit.y),
            //     transform.position.y,
            //     Mathf.Clamp(transform.position.z, zLimit.x, zLimit.y)
            // );
        }
    }
}

可选优化(适配斜俯视角RTS类相机)

如果你用的是45度倾斜俯视角相机,想要拖拽方向和玩家视角对齐(鼠标左右拖动时相机沿屏幕左右方向平移),可以替换Update内的逻辑:

if (Input.GetMouseButton(0)) 
{
    float xInput = Input.GetAxis("Mouse X") * panSpeed * Time.deltaTime;
    float zInput = Input.GetAxis("Mouse Y") * panSpeed * Time.deltaTime;

    // 计算忽略Y轴高度的相机右方向、前方向,保证移动始终在XZ平面
    Vector3 cameraRight = transform.right;
    cameraRight.y = 0;
    cameraRight.Normalize();
    Vector3 cameraForward = transform.forward;
    cameraForward.y = 0;
    cameraForward.Normalize();

    Vector3 moveDir = -xInput * cameraRight - zInput * cameraForward;
    transform.Translate(moveDir, Space.World);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:54:04