【问题标题】:Custom C++ Quaternion Rotation Not Working Correctly自定义 C++ 四元数旋转无法正常工作
【发布时间】: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


【解决方案1】:

在矢量旋转中将第一行替换为

Quaternion rotated = rotation * Quaternion(this->x, this->y, this->z, 0) * 
    rotation.conjugate();

解释:四元数乘法不可交换,这意味着 Q * v 不等于 v * Q,其中 v 是 w=0 的四元数。

【讨论】:

  • 我把它放入代码中,它没有改变任何东西,我得到了完全相同的结果。我试图改变这个乘法的顺序,有趣的是一些方法修复了错误的方向问题,以至于它们有时正好相反,但导致了 z 轴上不应该发生的旋转。无论如何感谢您的帮助。
【解决方案2】:

我最终决定将 GLM 纳入我的数学课,经过一些更改后,一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    相关资源
    最近更新 更多