2015-06-13 60 views
1

在我的代碼中,我有一個四元數用於旋轉玩家的相機。旋轉本身似乎很好,但我的移動和旋轉的方向矢量不能正確旋轉。自定義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到我的數學課和一些事情的變化後,一切正常,因爲它應該。

+1

將所有代碼縮進另外4個空格將使其更容易閱讀 – rds504

+1

您可以給出一個示例(數字!)的事情出錯,即您的輸入,輸出和預期結果。 –

+0

@ rds504好的,謝謝你的提示,我更新了這篇文章。 –

回答

0

我最終決定只是將GLM整合到我的數學課堂中,並且在事情發生一些變化之後,所有事情都會像應該那樣工作。

2

在您的矢量旋轉通過

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

說明代替第一行:四元數乘法是不可交換的,這意味着Q * V不等於V * Q,其中v爲以w = 0四元數。

+0

我把這個代碼放到了代碼中,沒有改變任何東西,我有完全相同的結果。我試圖改變這種乘法的順序,有趣的是有些方法將錯誤的方向問題固定在某種程度上,以至於它們有時恰好相反,但是導致z軸上的旋轉不應該發生。無論如何感謝您的幫助。 –