Unity 物体旋转

    在Unity中经常会用到物体的旋转,常用的方式一般是使用欧拉角和四元数。

欧拉角:

this.transform.eulerAngles

Demo:

    private void OnGUI()
    {
        if (GUILayout.Button("x 轴旋转"))
        {
            this.transform.eulerAngles += new Vector3(1, 0, 0);
        }
        if (GUILayout.Button("y 轴旋转"))
        {
            this.transform.eulerAngles += new Vector3(0, 1, 0);
        }
        if (GUILayout.Button("z 轴旋转"))
        {
            this.transform.eulerAngles += new Vector3(0, 0, 1);
        }

    }

   让物体分别绕x,y,z轴旋转 1 rad。

   这里有个问题,当物体绕x轴旋转90度之后,再让y或z轴继续旋转,会发现,物体只能绕

扫描二维码关注公众号,回复: 16810069 查看本文章

  y轴旋转。出现这种现象的原因是死锁了。欧拉角自身无法解决,需要利用四元数解决。

四元数:

this.transform.rotation

     使用四元数旋转可以解决万向节死锁问题,代码如下:

    private void OnGUI()
    {
        if (GUILayout.Button("x 轴旋转"))
        {
            this.transform.rotation *= Quaternion.AngleAxis(1, new Vector3(1, 0, 0));
        }
        if (GUILayout.Button("y 轴旋转"))
        {
            this.transform.rotation *= Quaternion.AngleAxis(1, new Vector3(0, 1, 0));
        }
        if (GUILayout.Button("z 轴旋转"))
        {
            this.transform.rotation *= Quaternion.AngleAxis(1, new Vector3(0, 0, 1));
        }

    }

   这样可以绕 x, y, z轴做任意旋转了。

在开发中比较常用的是Rotate旋转,里面实现也是利用四元数。因此平时开发使用Rotate即可:

    private void OnGUI()
    {
        if (GUILayout.Button("x 轴旋转"))
        {
            this.transform.Rotate(new Vector3(1, 0, 0), 1);
        }
        if (GUILayout.Button("y 轴旋转"))
        {
            this.transform.Rotate(new Vector3(0, 1, 0), 1);
        }
        if (GUILayout.Button("z 轴旋转"))
        {
            this.transform.Rotate(new Vector3(0, 0, 1), 1);
        }

    }

猜你喜欢

转载自blog.csdn.net/jake9602/article/details/128274969
今日推荐