在我的代碼中,我有一個四元數用於旋轉玩家的相機。旋轉本身似乎很好,但我的移動和旋轉的方向矢量不能正確旋轉。自定義C++四元數旋轉不能正確工作
四元數乘法:
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.
我一直在瀏覽谷歌和其他人的代碼在過去的幾天試圖找到我做錯了什麼,但我找不到任何錯誤。
UPDATE:
我最終決定只納入GLM到我的數學課和一些事情的變化後,一切正常,因爲它應該。
將所有代碼縮進另外4個空格將使其更容易閱讀 – rds504
您可以給出一個示例(數字!)的事情出錯,即您的輸入,輸出和預期結果。 –
@ rds504好的,謝謝你的提示,我更新了這篇文章。 –