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

Unity中鼠标旋转仅在游戏失焦时生效的问题求助

问题解决:Unity 3D飞行游戏鼠标旋转异常

问题分析

  1. 原代码核心问题:你的初始代码仅完成了鼠标与屏幕中心偏移量的计算,但没有将计算结果应用到飞船的旋转操作上,等于只做了数据准备,没执行实际旋转。另外未处理光标重置,鼠标移到屏幕边缘后无法持续提供有效输入。
  2. Brackey代码失效原因:左右旋转回弹是因为player.Rotate(Vector3.up * mouseX)的逻辑与你的飞船层级/其他代码冲突——如果player不是飞船根物体,或是有其他脚本在重置Y轴旋转值,就会出现旋转后立刻回弹的情况。

修正方案

方案1:修复初始代码(基于鼠标位置偏移)

补全旋转逻辑,添加光标重置,确保游戏聚焦时鼠标输入持续有效:

public float rotationSpeed = 5f;
private Vector2 screenCenter;

private void Start()
{
    screenCenter.x = Screen.width * 0.5f;
    screenCenter.y = Screen.height * 0.5f;
    // 锁定光标并隐藏,避免鼠标移出窗口
    Cursor.lockState = CursorLockMode.Locked;
    Cursor.visible = false;
}

private void Update()
{
    Rotate();
}

private void Rotate()
{
    Vector2 mousePosition = Input.mousePosition;
    // 计算鼠标偏移比例
    float xOffset = (mousePosition.x - screenCenter.x) / screenCenter.x;
    float yOffset = (mousePosition.y - screenCenter.y) / screenCenter.y;

    // 应用旋转:X轴控制俯仰,Y轴控制偏航
    transform.Rotate(Vector3.right, -yOffset * rotationSpeed * Time.deltaTime);
    transform.Rotate(Vector3.up, xOffset * rotationSpeed * Time.deltaTime);

    // 重置光标到屏幕中心,避免鼠标移出窗口
    Cursor.SetPosition(screenCenter.x, screenCenter.y);
}

方案2:修复Brackey的代码(基于鼠标轴输入)

调整旋转逻辑,让左右旋转直接作用于飞船,规避层级冲突:

public float mouseSensitivity = 100f;
float xRotation = 0f;
float yRotation = 0f;

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

private void Update()
{
    Rotate();
}

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

    // 上下旋转(俯仰),限制角度避免过度翻转
    xRotation -= mouseY;
    xRotation = Mathf.Clamp(xRotation, -80f, 80f);

    // 左右旋转(偏航)
    yRotation += mouseX;

    // 直接设置飞船整体旋转,避免层级冲突
    transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0f);
}

关键注意事项

  • 排查是否有其他脚本修改飞船的旋转值(比如移动脚本误操作transform.rotation)。
  • 测试时暂时关闭无关脚本,确认是否存在代码冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 02:17:50