首页 > 解决方案 > 旋转 90 度统一

问题描述

我正在尝试围绕我的鼠标旋转我的 2d 对象。这是我拥有的代码:

void Update()
    {
        Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector3 direction = mousePosition - transform.position;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
          transform.rotation = Quaternion.Euler(0, 0, angle);
       // Debug.Log(angle);
    }

我的对象是一个箭头,默认情况下是向下的,所以在我开始脚本之前我将它的z旋转设置为90,所以它面向右。如果我删除transform.rotation线,显示的角度将是正确的,当我的光标在上面写着 90,在左边写着 180 等等。所以我的问题是,为什么我需要在角度上加上 90 度才能使它真正起作用?为什么这个版本不起作用?谢谢!

标签: cunity3drotationgame-physics

解决方案


Mathf.Atan2(另见维基百科 - Atan2

返回值是x 轴[= Vector3.right] 和从零开始到 (x,y) 终止的二维向量之间的角度。

如果默认情况下您的箭头指向右侧但您的箭头指向右侧,它将按预期工作

默认指向下方


您可以简单地在顶部添加偏移旋转,例如

transform.rotation = Quaternion.Euler(0, 0, angle + 90);

或者,如果您需要具有不同偏移量的多个对象,请使用可配置字段,例如

[SerializeField] private float angleOffset;

...

transform.rotation = Quaternion.Euler(0, 0, angle + angleOffset);

或者您可以在启动应用程序之前手动旋转它以正确面向右侧并存储默认的偏移旋转,例如

private Quaternion defaultRotation;

private void Awake ()
{
    defaultRotation = transform.rotation;
}

然后做

transform.rotation = defaultRotation * Quaternion.Euler(0, 0, angle);

推荐阅读