问题记录(自用)
Unity物体旋转问题
物体旋转:直接修改transform.right=direction旋转出错
代码理解
Transform类中的 forward/up/right 定义
https://github.com/Unity-Technologies/UnityCsReference
// The red axis of the transform in world space.
public Vector3 right { get { return rotation * Vector3.right; } set { rotation = Quaternion.FromToRotation(Vector3.right, value); } }
// The green axis of the transform in world space.
public Vector3 up { get { return rotation * Vector3.up; } set { rotation = Quaternion.FromToRotation(Vector3.up, value); } }
// The blue axis of the transform in world space.
public Vector3 forward { get { return rotation * Vector3.forward; } set { rotation = Quaternion.LookRotation(value); } }
问题
在set属性中,使用Quaternion.FromToRotation创建四元数,起始位置用的是世界坐标轴的right和up
旋转出错是因为物体的起始位置不正确
解决方法
- 给物体加一个空的父物体,使用父节点进行旋转
- 不使用transform的right进行设置,在物体原来旋转的基础上进行旋转叠加。代码如下:
var rot = Quaternion.FromToRotation(transform.right, direction);
transform.rotation = rot * transform.rotation;
本文探讨了在Unity中直接修改物体transform.right导致旋转错误的问题。问题源于使用世界坐标轴的right和up进行旋转时,起始位置不正确。解决方法是为物体添加空父对象,并基于父对象的旋转进行叠加,通过Quaternion.FromToRotation计算新的旋转。代码示例展示了如何正确实现物体的旋转操作。
1208

被折叠的 条评论
为什么被折叠?



