【发布时间】:2015-06-13 14:11:09
【问题描述】:
在我的代码中,我有一个四元数,用于为玩家的相机旋转。旋转本身似乎工作正常,但我用于移动和旋转的方向矢量无法正确旋转。
四元数乘法:
Quaternion Quaternion::operator*(Vector3 other) const
{
float x_ = w * other.x + y * other.z - z * other.y;
float y_ = w * other.y + z * other.x - x * other.z;
float z_ = w * other.z + x * other.y - y * other.x;
float w_ = -x * other.x - y * other.y - z * other.z;
return Quaternion(x_, y_, z_, w_);
}
Quaternion Quaternion::operator*(Quaternion other) const
{
Vector4 r = other.getValues();
float x_ = x * r.w + w * r.x + y * r.z - z * r.y;
float y_ = y * r.w + w * r.y + z * r.x - x * r.z;
float z_ = z * r.w + w * r.z + x * r.y - y * r.x;
float w_ = w * r.w - x * r.x - y * r.y - z * r.z;
return Quaternion(x_, y_, z_, w_);
}
共轭函数
Quaternion Quaternion::conjugate() const
{
return Quaternion(-x, -y, -z, w);
}
矢量旋转:
void Vector3::rotate(Quaternion rotation)
{
Quaternion rotated = rotation * *this * rotation.conjugate();
x = rotated.getValues().x;
y = rotated.getValues().y;
z = rotated.getValues().z;
}
样本方向向量:
Vector3 Quaternion::getRight() const
{
Vector3 right(1.0f, 0.0f, 0.0f);
right.rotate(*this);
return right;
}
如果我让相机围绕 y 轴精确旋转 90 度并打印出右向量的值,x 是 0.000796229,y 是 0,z 是 -1。在这种情况下,x 应为 0,z 应为正 1。
过去几天我一直在浏览 Google 和其他人的代码,试图找出我做错了什么,但我找不到任何错误。
更新:
我最终决定将 GLM 纳入我的数学课,经过一些更改后,一切正常。
【问题讨论】:
-
将所有代码缩进另外 4 个空格会更容易阅读
-
你能举一个出错的例子(数字!),即你的输入、输出和预期结果。
-
绝对不是问题的一部分,但您可以使用
other.x而不是other.getX()使代码更易于阅读。 -
也尝试调试您的代码。在调试器中检查算法,看看它与您的期望有何不同
标签: c++ rotation vector-graphics quaternions