这里有一些背景:我正在开发一个游戏引擎,我最近添加了一个物理引擎(在本例中为 physx)。问题是我的变换类使用欧拉角进行旋转,而物理引擎的变换类使用欧拉角。所以我刚刚实现了一个方法来将我的变换类更改为物理引擎变换并返回。它运行良好,但我发现了一个奇怪的错误。
我得到的行为:
当旋转的偏航(欧拉矢量的第二个元素)高于 90 度时,它不会使对象在 y 轴上再旋转并开始与俯仰和滚动搞乱(奇怪的摇晃从 0 跳到 180 和回来很多)。调试工具显示旋转不会超过 91,但会达到最大 90.0003 我确实将度数转换为弧度。 示例: 为了显示这个错误,我有一个带有 python 脚本旋转它的立方体:
from TOEngine import *
class rotate:
direction = vec3(0,10,0)
def Start(self):
pass
def Update(self,deltaTime):
transform.Rotate(self.direction*deltaTime*5)
pass
引擎本身是用 cpp 编写的,但我有一个使用嵌入式 python 的脚本系统。TOEngine 只是我的模块,脚本本身只是每帧旋转立方体。立方体从 0 , 0 , 0 旋转开始,旋转很好,但停止,90 度偏航并开始摇晃。
这仅在启用物理系统时发生,因此我知道错误必须在使用 glm 将旋转从 euler 传输到 quat 并返回每一帧的方法中。
这是实际有问题的代码:
void RigidBody::SetTransform(Transform transform)
{
glm::vec3 axis = transform.rotation;
rigidbody->setGlobalPose(PxTransform(*(PxVec3*)&transform.position,*(PxQuat*)&glm::quat(glm::radians(transform.rotation))));//Attention Over Here
}
Transform RigidBody::GetTransform()
{
auto t = rigidbody->getGlobalPose();
return Transform(*(glm::vec3*)&t.p, glm::degrees(glm::eulerAngles(*(glm::quat*)&t.q)), entity->transform.scale);
}
避免奇怪的类型双关语 PxQuat 与 glm::quat 基本相同,PxVec3 与 glm::vec3 基本相同。我希望此代码通过将旋转从欧拉角角度更改为带有弧度的 quat(困难部分),在物理引擎变换类和我的变换类之间传输。
以及物理系统内部:
void PreUpdate(float deltaTime)override { //Set Physics simulation changes to the scene
mScene->fetchResults(true);
for (auto entity : Events::scene->entities)
for (auto component : entity->components)
if (component->GetName() == "RigidBody")
entity->transform = ((RigidBody*)component)->GetTransform(); //This is running on the cube entity
}
void PostUpdate(float deltaTime)override { //Set Scene changes To Physics simulation
for (auto entity : Events::scene->entities)
for (auto component : entity->components)
if (component->GetName() == "RigidBody")
((RigidBody*)component)->SetTransform(entity->transform);//This is running on the cube entity
mScene->simulate(deltaTime);
}
PreUpdate 在每帧更新之前运行 PostUpdate 在每帧更新之后运行。顾名思义,Update 方法(在上面的脚本中显示)在更新上运行...(在 PreUpdate 和 PostUpdate 之间)。立方体有一个刚体组件。我期望得到:一个旋转的立方体,当它达到 90 度偏航时不会停止旋转。
我知道这个有点复杂。我尽力解释了我认为问题在于将欧拉角更改为四元组的错误。