Unity 使用 Quaternion 类来存储游戏对象的三维方向,也使用它们来描述从一个方向到另一个方向的相对旋转。
此页面概述了 Quaternion 类及其在脚本编写中的常见用法。如需了解 Quaternion 类的所有成员的详尽参考信息,请参阅 Quaternion 脚本参考。
请务必理解欧拉角(检视面板中显示的规定GameObject旋转的 X、Y、Z 值)以及 Unity 用来存储__ GameObject__Unity 场景中的基础对象,可以表示角色、道具、风景、摄像机、路径点等。GameObject 的功能由所附的组件决定。更多信息
See in Glossary 实际旋转的底层 Quaternion 值之间的区别。如需了解本主题的基础知识,请阅读 Unity 中的旋转和方向.
处理脚本中的旋转时,应使用 Quaternion 类及其函数来创建和修改旋转值。在某些情况下,使用欧拉角也是有效的,但应记住: - 应使用处理欧拉角的 Quaternion 类函数 - 从旋转中检索、修改和重新应用欧拉值可能会导致意外的副作用(参阅下文)
Unity 的 Quaternion 类拥有许多无需使用欧拉角就能为创建和操作旋转而服务的函数,它们也是大多数典型用例会用到的函数。下方每一个函数都指向了带有代码示例的脚本参考:
Transform 类还提供了一些方法可用于处理 Quaternion 旋转:
某些情况更适合在脚本中使用欧拉角。这时请务必注意,必须将角度保存在变量中,并在使用的时候仅将它们作为欧拉角应用于旋转,从而将其最终存储为 Quaternion。虽然可以通过 Quaternion 获取欧拉角,但获取、修改和重新应用时可能会出现问题。
如需了解这些问题的详细成因,请阅读 eulerAngles 脚本参考页面。
下面是一些常犯错误的示例:假设示例将尝试围绕 X 轴以每秒 10 度的速度旋转 GameObject。应避免此类情况:
// rotation scripting mistake #1
// the mistake here is that we are modifying the x value of a quaternion
// this value does not represent an angle, and does not produce desired results
void Update ()
{
var rot = transform.rotation;
rot.x += Time.deltaTime * 10;
transform.rotation = rot;
}
// rotation scripting mistake #2
// Read, modify, then write the Euler values from a Quaternion.
// Because these values are calculated from a Quaternion,
// each new rotation might return very different Euler angles, which might suffer from gimbal lock.
void Update ()
{
var angles = transform.rotation.eulerAngles;
angles.x += Time.deltaTime * 10;
transform.rotation = Quaternion.Euler(angles);
}
下方是在脚本中正确使用欧拉角的示例:
// Rotation scripting with Euler angles correctly.
// Store the Euler angle in a class variable, and only use it to
// apply it as an Euler angle, but never rely on reading the Euler back.
float x;
void Update ()
{
x += Time.deltaTime * 10;
transform.rotation = Quaternion.Euler(x,0,0);
}