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

Unity顶视角3D场景中GameObject绕玩家随鼠标旋转角度偏移问题

3D场景中GameObject随鼠标绕Player旋转的90度角度偏差问题

我是Unity新手,尝试实现GameObject随鼠标方向绕Player旋转,目前功能可运行,但旋转角度与预期存在90度偏差。看过不少2D场景的相关教程,无法直接适配3D场景。

当前层级结构

层级结构为:Player(父对象)→ Rotate Point(子对象,挂载Launcher脚本)→ Projectile Transform(Rotate Point的子对象)

RotatePoint挂载的脚本代码

using UnityEngine;

public class Launcher : MonoBehaviour
{
    private Camera mainCamera;
    private Vector3 mousePos;

    private void Start()
    {
        mainCamera = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
    }

    private void Update()
    {
        faceMouse();
    }

    private void faceMouse()
    {
        mousePos = mainCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,
   Input.mousePosition.y, Camera.main.nearClipPlane));

        Vector3 distence = mousePos - transform.position;
        Quaternion rotation = Quaternion.LookRotation(distence);

        transform.rotation = Quaternion.RotateTowards(transform.rotation, rotation, 1);
    }
}

相关组件配置

对应组件截图信息:Player、Main Camera、Rotate Point、Projectile Transform的组件参数截图。


问题原因与修正方案

问题核心是Quaternion.LookRotation()的默认轴向逻辑:3D中该方法会让物体的**Z轴(forward方向)**指向目标点,但如果你的RotatePoint模型的预期朝向轴不是Z轴(比如模型前向是X/Y轴),就会出现90度偏差。

修正步骤:

  1. 统一相机引用:原代码中混用mainCamera和Camera.main,改成只用已获取的mainCamera,避免重复查找影响性能:

    mousePos = mainCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, mainCamera.nearClipPlane));
    
  2. 添加轴向补偿旋转:根据模型的实际朝向轴,给目标旋转添加补偿角度。比如如果模型前向是X轴,就添加绕Y轴90度的旋转;如果是Y轴则绕X轴调整。示例代码:

    private void faceMouse()
    {
        mousePos = mainCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, mainCamera.nearClipPlane));
        Vector3 direction = mousePos - transform.position;
        // 如果是平面旋转(比如TopDown视角),可忽略Y轴避免上下旋转
        direction.y = 0;
        Quaternion targetRotation = Quaternion.LookRotation(direction);
        // 这里以绕X轴旋转90度为例,根据你的模型朝向调整轴和角度
        targetRotation *= Quaternion.Euler(90, 0, 0);
        transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, 1);
    }
    
  3. 验证轴向匹配:在Scene视图中查看RotatePoint的Gizmos轴(红色X、绿色Y、蓝色Z),确认哪个轴是模型需要朝向鼠标的方向,调整补偿欧拉角的数值和轴向即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:40:57