Unity 使用 Quaternion 类来存储游戏对象的三维方向,也使用它们来描述从一个方向到另一个方向的相对旋转。
此页面概述 Quaternion 类及其在脚本编写中的常见用法。有关 Quaternion 类的每个成员的详尽参考,请参阅 Quaternion 脚本参考。
了解欧拉角(在检查器中看到的用于游戏对象旋转的 X、Y、Z 值),以及 Unity 用于存储游戏对象实际旋转的基础 Quaternion 值。有关本主题的基础知识,请阅读 Unity 中的旋转和方向.
处理脚本中的旋转时,应使用 Quaternion 类及其函数来创建和修改旋转值。在某些情况下,使用欧拉角也是有效的,但应记住: - 应使用处理欧拉角的 Quaternion 类函数 - 从旋转中检索、修改和重新应用欧拉值可能会导致意外的副作用(参阅下文)
Unity 的 Quaternion 类具有许多函数可用于创建和操作旋转,根本无需使用欧拉角,下面是大多数典型用例中使用的函数。每一个都指向带有代码示例的脚本参考:
Transform 类还提供了一些方法可用于处理 Quaternion 旋转:
某些情况下,更适合在脚本中使用欧拉角。这时,请务必注意,必须将角度保存在变量中,在使用它们的时候,仅将它们作为欧拉角应用于旋转,最终仍应存储为 Quaternion。虽然可从四元数中获取欧拉角,但在获取、修改和重新应用时,可能会出现问题。
可以在 eulerAngles 脚本参考页面中阅读更多有关这些问题究竟如何发生的详细信息。
下面是一些常犯错误的示例:使用假设的示例来尝试围绕 X 轴以每秒 10 度的速度旋转游戏对象。应避免此类情况:
// 旋转脚本错误 #1
// 此处的错误在于我们正在修改四元数的 x 值
// 此值不表示角度,不会产生所需的结果
void Update ()
{
var rot = transform.rotation;
rot.x += Time.deltaTime * 10;
transform.rotation = rot;
}
// 旋转脚本错误 #2
// 从四元数读取、修改并写入欧拉值。
// 因为这些值是从四元数计算的,
// 所以每个新的旋转可能会返回非常不同的欧拉角,而这可能会受到万向锁的影响。
void Update ()
{
var angles = transform.rotation.eulerAngles;
angles.x += Time.deltaTime * 10;
transform.rotation = Quaternion.Euler(angles);
}
以下是在脚本中正确使用欧拉角的示例:
// 正确使用欧拉角的旋转脚本。
// 将欧拉角存储在一个类变量中,并仅使用
// 该变量作为欧拉角进行应用,但从不依赖于读回欧拉值。
float x;
void Update ()
{
x += Time.deltaTime * 10;
transform.rotation = Quaternion.Euler(x,0,0);
}
有关更多信息,请参阅 Quaternion 脚本参考。
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.