旋转 90 度统一
Rotation off by 90 degrees unity
我试图围绕我的鼠标旋转我的 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 度角让它真正起作用?为什么这个版本不起作用?
Mathf.Atan2
(Also see Wikipedia - Atan2)
Return value is the angle between the x-axis [=Vector3.right
] and a 2D vector starting at zero and terminating at (x,y).
如果默认情况下您的箭头指向右侧但您的箭头指向右侧,则它会按预期工作
by default pointing down
你可以像
一样简单地在顶部添加偏移旋转
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);
我试图围绕我的鼠标旋转我的 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 度角让它真正起作用?为什么这个版本不起作用?
Mathf.Atan2
(Also see Wikipedia - Atan2)
Return value is the angle between the x-axis [=
Vector3.right
] and a 2D vector starting at zero and terminating at (x,y).
如果默认情况下您的箭头指向右侧但您的箭头指向右侧,则它会按预期工作
by default pointing down
你可以像
一样简单地在顶部添加偏移旋转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);