Version: 2022.3
public Vector3 eulerAngles ;

描述

返回或设置旋转的欧拉角表示。

欧拉角可以通过围绕各个轴执行三个单独的旋转来表示三维旋转。在 Unity 中,围绕 Z 轴、X 轴和 Y 轴(按该顺序)执行这些旋转。

可以通过设置此属性来设置四元数的旋转,并且可以通过读取此属性来读取欧拉角的值。

使用 .eulerAngles 属性设置旋转时,务必要了解,虽然提供 X、Y 和 Z 旋转值描述旋转,但是这些值不存储在旋转中。而是将 X、Y 和 Z 值转换为四元数的内部格式。

读取 .eulerAngles 属性时,Unity 将四元数的内部旋转表示形式转换为欧拉角。因为可通过多种方式使用欧拉角表示任何给定旋转,所以读出的值可能与分配的值截然不同。如果尝试逐渐增加值以生成动画,则这种情况可能会导致混淆。有关更多信息,请参阅底部的脚本示例。

若要避免这些类型的问题,使用旋转的建议方式是避免在读取 .eulerAngles 时依赖一致的结果,特别是在尝试逐渐增加旋转以生成动画时。有关实现此目标的更佳方式,请参阅四元数 * 运算符

以下示例说明基于用户的输入使用 eulerAngles 旋转 GameObject。该示例说明我们从不依赖于读取 Quanternion.eulerAngles 来增加旋转,而是使用 Vector3 currentEulerAngles 来设置它。所有旋转更改都在 currentEulerAngles 变量中进行,这些更改随后应用于四元数,从而避免上面提到的问题。

using UnityEngine;
public class ExampleScript : MonoBehaviour
{
    float rotationSpeed = 45;
    Vector3 currentEulerAngles;
    Quaternion currentRotation;
    float x;
    float y;
    float z;

void Update() { if (Input.GetKeyDown(KeyCode.X)) x = 1 - x; if (Input.GetKeyDown(KeyCode.Y)) y = 1 - y; if (Input.GetKeyDown(KeyCode.Z)) z = 1 - z;

//modifying the Vector3, based on input multiplied by speed and time currentEulerAngles += new Vector3(x, y, z) * Time.deltaTime * rotationSpeed;

//moving the value of the Vector3 into Quanternion.eulerAngle format currentRotation.eulerAngles = currentEulerAngles;

//apply the Quaternion.eulerAngles change to the gameObject transform.rotation = currentRotation; }

void OnGUI() { GUIStyle style = new GUIStyle(); style.fontSize = 24; // Use eulerAngles to show the euler angles of the quaternion stored in Transform.Rotation GUI.Label(new Rect(10, 0, 0, 0), "Rotating on X:" + x + " Y:" + y + " Z:" + z, style);

//outputs the Quanternion.eulerAngles value GUI.Label(new Rect(10, 25, 0, 0), "CurrentEulerAngles: " + currentEulerAngles, style);

//outputs the transform.eulerAngles of the GameObject GUI.Label(new Rect(10, 50, 0, 0), "GameObject World Euler Angles: " + transform.eulerAngles, style); } }

以下示例说明从 .eulerAngles 读出的值如何与分配的值截然不同,即使它们表示相同旋转。

using UnityEngine;

// demonstration of eulerAngles not returning the same values as assigned public class EulerAnglesProblemExample : MonoBehaviour { private void Start() { Quaternion myRotation = Quaternion.identity; myRotation.eulerAngles = new Vector3(150, 35, 45);

Debug.Log(myRotation.eulerAngles);

// output is: (30.0, 215.0, 225.0) } }