面对轴时绕轴旋转
Rotation around axis while facing along it
以下两行,在 Update() 中,确保我的 Transform 始终以设定的旋转角度(this.Rotation,一个范围为 0 的浮点数面向前方(this.Point.forward) - 360) 绕着前向轴。
this.transform.rotation = Quaternion.AngleAxis(this.Rotation, this.Point.forward);
this.transform.rotation = Quaternion.LookRotation(this.Point.forward, this.transform.up);
但是,由于一些原因,现在我想smooth/lerp轮换;因此,我没有直接设置“this.transform.rotation”,而是在 class 中添加了一个“targetRotation”属性,并将这些行更改为;
targetRotation = Quaternion.AngleAxis(this.Rotation, this.Point.forward);
targetRotation = Quaternion.LookRotation(this.Point.forward, this.transform.up);
并添加;
this.transform.rotation = Quaternion.Slerp(
this.transform.rotation,
targetRotation,
this.rotationSpeed * Time.deltaTime
);
更改的(明显)问题是 targetRotation 的第二个分配替换了第一个。
我不确定如何以复制直接设置变换旋转时所发生情况的方式组合四元数运算。
我尝试将它们相乘,但这导致旋转旋转得越来越快,而不是仅仅坚持 this.Rotation 的值。
谢谢!
首先,围绕this.Point.forward
旋转全局向上旋转。您可以使用 *
运算符来执行此操作:
Vector3 upDir = Quaternion.AngleAxis(this.Rotation, this.Point.forward) * Vector3.up;
然后向上旋转,像以前一样进行:
targetRotation = Quaternion.LookRotation(this.Point.forward, upDir);
this.transform.rotation = Quaternion.Slerp(
this.transform.rotation,
targetRotation,
this.rotationSpeed * Time.deltaTime
);
顺便说一下,使用 Lerp/Slerp 函数和永远不会保证等于或超过 1 的 t
可能会由于舍入错误而容易出错,如果您需要保证输出将最终完全等于目标。
如果不需要那个保证,这里的答案就可以了。
如果需要保证,请考虑使用其他东西(例如 rotateTowards
)代替 Slerp
。
以下两行,在 Update() 中,确保我的 Transform 始终以设定的旋转角度(this.Rotation,一个范围为 0 的浮点数面向前方(this.Point.forward) - 360) 绕着前向轴。
this.transform.rotation = Quaternion.AngleAxis(this.Rotation, this.Point.forward);
this.transform.rotation = Quaternion.LookRotation(this.Point.forward, this.transform.up);
但是,由于一些原因,现在我想smooth/lerp轮换;因此,我没有直接设置“this.transform.rotation”,而是在 class 中添加了一个“targetRotation”属性,并将这些行更改为;
targetRotation = Quaternion.AngleAxis(this.Rotation, this.Point.forward);
targetRotation = Quaternion.LookRotation(this.Point.forward, this.transform.up);
并添加;
this.transform.rotation = Quaternion.Slerp(
this.transform.rotation,
targetRotation,
this.rotationSpeed * Time.deltaTime
);
更改的(明显)问题是 targetRotation 的第二个分配替换了第一个。
我不确定如何以复制直接设置变换旋转时所发生情况的方式组合四元数运算。
我尝试将它们相乘,但这导致旋转旋转得越来越快,而不是仅仅坚持 this.Rotation 的值。
谢谢!
首先,围绕this.Point.forward
旋转全局向上旋转。您可以使用 *
运算符来执行此操作:
Vector3 upDir = Quaternion.AngleAxis(this.Rotation, this.Point.forward) * Vector3.up;
然后向上旋转,像以前一样进行:
targetRotation = Quaternion.LookRotation(this.Point.forward, upDir);
this.transform.rotation = Quaternion.Slerp(
this.transform.rotation,
targetRotation,
this.rotationSpeed * Time.deltaTime
);
顺便说一下,使用 Lerp/Slerp 函数和永远不会保证等于或超过 1 的 t
可能会由于舍入错误而容易出错,如果您需要保证输出将最终完全等于目标。
如果不需要那个保证,这里的答案就可以了。
如果需要保证,请考虑使用其他东西(例如 rotateTowards
)代替 Slerp
。