Unity 实用教程之 EulerAngles的使用

2025-10-26 20:32:22

1、Transform.eulerAngles:

The rotation as Euler angles in degrees.

The x, y, and z angles represent a rotation z degrees around the z axis, x degrees around the x axis, and y degrees around the y axis.Only use this variable to read and set the angles to absolute values. Don't increment them, as it will fail when the angle exceeds 360 degrees. Use Transform.Rotate instead.

1、打开Unity,新建一个空工程,具体如下图

Unity 实用教程之 EulerAngles的使用

2、在工程中新建一个脚本 EulerAngles ,双击脚本或有右键“Open C# Project”打开脚本进行编辑,具体如下图

Unity 实用教程之 EulerAngles的使用

3、EulerAngles 脚本,在 Update 函数中分别按下 X、Y、Z键 对应增加X、Y、Z大小值,并调用函数 PrintEulerAngles 打印结果,具体代码如下图

Unity 实用教程之 EulerAngles的使用

Unity 实用教程之 EulerAngles的使用

4、EulerAngles 脚本具体内容如下:

using UnityEngine;

public class EulerAngles : MonoBehaviour {

// Use this for initialization

void Start () {

}

// Update is called once per frame

void Update () {

        if (Input.GetKeyDown(KeyCode.X)) {

            transform.localEulerAngles= new Vector3(

                transform.localEulerAngles.x + 10,

                transform.localEulerAngles.y,

                transform.localEulerAngles.z);

            PrintEulerAngles();

        }

        if (Input.GetKeyDown(KeyCode.Y))

        {

            transform.localEulerAngles = new Vector3(

                transform.localEulerAngles.x,

                transform.localEulerAngles.y + 10,

                transform.localEulerAngles.z);

            PrintEulerAngles();

        }

        if (Input.GetKeyDown(KeyCode.Z))

        {

            transform.localEulerAngles = new Vector3(

                transform.localEulerAngles.x,

                transform.localEulerAngles.y,

                transform.localEulerAngles.z + 10);

            PrintEulerAngles();

        }

    }

    private void PrintEulerAngles() {

        print("transform.localEulerAngles:" + transform.localEulerAngles);

        print("transform.localEulerAngles.x:" + transform.localEulerAngles.x);

        print("transform.localEulerAngles.y:" + transform.localEulerAngles.y);

        print("transform.localEulerAngles.z:" + transform.localEulerAngles.z);

    }

}

5、脚本编译正确,回到Unity界面,在场景中添加一个 GameObject ,并挂载脚本,具体如下图

Unity 实用教程之 EulerAngles的使用

6、运行场景,分别按下 X、Y、Z,你会发现,EulerAngles 能获得真正的角度值,而Rotation获得的不是而是通过转换后的值,打印结果如下图

Unity 实用教程之 EulerAngles的使用

7、到此,《Unity 实用教程之 EulerAngles的使用》讲解结束,谢谢

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢