2013-09-27 135 views
0

我在DirectX11中有一個3D對象,它具有位置矢量和它面向的方向(它只能圍繞Y軸旋轉)的旋轉角度。計算3D對象和點之間的角度

D3DXVECTOR3 m_position; 
float  m_angle; 

如果我當時就想旋轉對象要面對的東西,那麼我需要找到它面對的方向,它需要使用點產品。兩個標準化向量面對的方向之間的角度。

我遇到問題的是我如何找到物體當前面對的方向,只是它的位置和角度。我現在擁有的是:

D3DXVECTOR3 normDirection, normTarget; 
D3DXVec3Normalize(&normDirection, ????); 
D3DXVec3Normalize(&normTarget, &(m_position-target)); 

// I store the values in degrees because I prefer it 
float angleToRotate = D3DXToDegree(acos(D3DXVec3Dot(&normDirection, &normTarget))); 

有誰知道我是如何得到它是從我的價值觀當前面臨方向的矢量,或者我需要重新寫,所以我跟蹤對象的方向向量?

編輯:改變'cos'爲'acos'。

溶液(user2802841的援助):

// assuming these are member variables 
D3DXVECTOR3 m_position; 
D3DXVECTOR3 m_rotation; 
D3DXVECTOR3 m_direction; 

// and these are local variables 
D3DXVECTOR3 target; // passed in as a parameter 
D3DXVECTOR3 targetNorm; 
D3DXVECTOR3 upVector; 
float angleToRotate; 

// find the amount to rotate by 
D3DXVec3Normalize(&targetNorm, &(target-m_position)); 
angleToRotate = D3DXToDegree(acos(D3DXVec3Dot(&targetNorm, &m_direction))); 

// calculate the up vector between the two vectors 
D3DXVec3Cross(&upVector, &m_direction, &targetNorm); 

// switch the angle to negative if the up vector is going down 
if(upVector.y < 0) 
    angleToRotate *= -1; 

// add the rotation to the object's overall rotation 
m_rotation.y += angleToRotate; 

回答

1

如果存儲的取向的角度,那麼你必須承擔某種默認方向時的角度爲0,表示的是默認的方向爲矢量(如果您假定x +方向爲默認值,則爲(1.0,0.0,0.0)),然後將該向量旋轉角度(或者使用directly with sin/cos或使用由one of the D3DXMatrixRotation*函數創建的旋轉矩陣),並且生成的向量將是您當前的方向。

編輯:

在回答您的意見,您可以確定旋轉方向like this。而你的情況轉化爲像(未經測試):

D3DXVECTOR3 cross; 
D3DXVec3Cross(&cross, &normDirection, &normTarget); 
float dot; 
D3DXVec3Dot(&dot, &cross, &normal); 
if (dot < 0) { 
    // angle is negative 
} else { 
    // angle is positive 
} 

哪裏normal是最有可能是(0,1,0)向量(因爲你說你的對象繞Y軸)。

+0

你究竟如何旋轉一個旋轉矩陣的向量?從我看到你不能做'D3DXVECTOR3 = D3DXVECTOR3 * D3DXMATRIX'。是的,我現在意識到,在我的程序中至少有0度==(0,0,1)。 – Edward

+0

@Edward Try [D3DXVec3TransformCoord](http://msdn.microsoft.com/en-us/library/windows/desktop/bb205522.aspx) – user2802841

+0

謝謝,這正是我需要的。另一個問題是由此產生的。如果將位置設置爲(5,3,0),目標位置設置爲(7.5,3,2.5),則將角度正確設置爲45度,但當設置目標爲7.5時角度仍然爲45度,3,-2.5)。有沒有確定旋轉方向的方法? – Edward

1

如果作爲你說,0度==(0,0,1),可以使用:

normDirection =(SIN(角度),0,COS(角度))

因爲旋轉總是圍繞y軸。

根據您的系統(左手或右手),您將不得不改變罪的標誌(角度)。