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轴继续旋转,会发现,物体只能绕

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);

}

————————————————

版权声明:本文为优快云博主「后知后觉」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.youkuaiyun.com/jake9602/article/details/128274969

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值