2015-08-08 63 views
0

我似乎無法讓我的相機根據其自身的本地軸進行旋轉。它只會圍繞X和Y旋轉的原點旋轉。Direct X中的相機旋轉11

POINT cursorPos; 
GetCursorPos(&cursorPos); 
LONG deltaX = oldCursorPos.x - cursorPos.x; 
LONG deltaY = oldCursorPos.y - cursorPos.y; 

if (GetAsyncKeyState(VK_RBUTTON)) 
{ 
    XMMATRIX xRotation = XMMatrixRotationY((-deltaX * (float)timer.Delta())); 
    XMMATRIX yRotation = XMMatrixRotationX((-deltaY * (float)timer.Delta())); 

    XMFLOAT4 viewVector = XMFLOAT4(sceneMatrix.viewMatrix.m[3][0], sceneMatrix.viewMatrix.m[3][1], sceneMatrix.viewMatrix.m[3][2], sceneMatrix.viewMatrix.m[3][3]); 
    XMVECTOR pos = XMLoadFloat4(&viewVector); 
    for (size_t i = 0; i < 4; i++) { sceneMatrix.viewMatrix.m[3][i] = 0.0f; } 
    XMMATRIX view = XMLoadFloat4x4(&sceneMatrix.viewMatrix); 

    view = xRotation * view; 
    view = view * yRotation; 

    XMStoreFloat4x4(&sceneMatrix.viewMatrix, view); 

    sceneMatrix.viewMatrix.m[3][0] = XMVectorGetX(pos); 
    sceneMatrix.viewMatrix.m[3][1] = XMVectorGetY(pos); 
    sceneMatrix.viewMatrix.m[3][2] = XMVectorGetZ(pos); 
    sceneMatrix.viewMatrix.m[3][3] = XMVectorGetW(pos); 
} 

oldCursorPos = cursorPos; 

起初我還以爲我是在錯誤的順序乘以他們,但是當我扭轉他們,我仍然旋轉圍繞原點。我無法挑選出我做錯了什麼。

+0

鑑於標量和矢量操作的所有混合,在這裏最好使用[SimpleMath](https://github.com/Microsoft/DirectXTK/wiki/SimpleMath)DirectXMath包裝器[ DirectX工具包](https://github.com/Microsoft/DirectXTK)。 –

回答

1

您需要的局部旋轉軸被構建到視圖矩陣中......種類。視圖矩陣是表示相機的世界空間位置和旋轉的矩陣的反轉形式。首先,您必須反轉視圖矩陣,然後攝像機的本地x軸是第一行,y軸是第2行,z軸是第3行。(或者您可以通過使用適當的列來提取局部向量)。那麼使用軸/角度版本代替XMMatrixRotationX,您可以插入這些本地軸:XMMatrixRotationAxisXMMatrixRotationNormal以進行旋轉。

1

這就是旋轉矩陣的工作原理。它們旋轉原點周圍的每個空間點。

RotationMatrix http://www.sharetechnote.com/image/EngMath_Matrix_Affin_Rotate.PNG

要旋轉相機繞Y軸比如你想設置X = 0 & Z = 0。然後應用旋轉矩陣(現在它尋找到不同的位置),然後移動相機回到原來的位置。

另一種選擇是創建一個視圖矩陣來爲你模擬整個攝像機,並在每一幀左右改變它。

+1

但他的原始代碼就是這樣。他的代碼片段記錄了他的視圖位置,將其設置爲零,旋轉其視圖矩陣,然後將視圖的位置重置爲原始位置,就像您的答案所示。你爲什麼建議他通過做他已經在做的事來解決他的問題? –

+0

我知道矩陣如何在3D空間中工作,問題在於即使按照**局部**相機旋轉的公式,我也沒有得到預期的結果。我意識到我沒有正確執行反向操作,導致了錯誤的旋轉。我試圖只使用視圖矩陣,但我的解決方案是創建一個相機矩陣,以處理旋轉和平移,並將視圖矩陣設置爲每幀相機矩陣的逆矩陣。謝謝你們倆! – Dakattack