2009-11-07 108 views
4

我將一個形狀表示爲一組3D座標,我試圖圍繞一個軸旋轉整個對象(在這種情況下,Z軸,但我想旋轉所有三個一旦我得到它的工作)。圍繞一個軸旋轉座標

我已經寫了一些代碼,這一點使用一個旋轉矩陣做:


//Coord is a 3D vector of floats 
//pos is a coordinate 
//angles is a 3d vector, each component is the angle of rotation around the component axis 
//in radians 
Coord<float> Polymers::rotateByMatrix(Coord<float> pos, const Coord<float> &angles) 
{ 
    float xrot = angles[0]; 
    float yrot = angles[1]; 
    float zrot = angles[2]; 

    //z axis rotation 
    pos[0] = (cosf(zrot) * pos[0] - (sinf(zrot) * pos[1])); 
    pos[1] = (sinf(zrot) * pos[0] + cosf(zrot) * pos[1]); 

    return pos; 
} 

下圖顯示了我想要旋轉(向下看Z軸)旋轉之前嘗試的對象,每個小球表示座標的一個我想旋轉

alt text http://www.cs.nott.ac.uk/~jqs/notsquashed.png

旋轉是由下面的代碼爲對象進行的:


//loop over each coordinate in the object 
for (int k=start; k<finish; ++k) 
{ 
    Coord<float> pos = mp[k-start]; 
    //move object away from origin to test rotation around origin 
    pos += Coord<float>(5.0,5.0,5.0); 

    pos = rotateByMatrix(pos, rots); 

    //wrap particle position 
    //these bits of code just wrap the coordinates around if the are 
    //outside of the volume, and write the results to the positions 
    //array and so shouldn't affect the rotation. 
    for (int l=0; l<3; ++l) 
    { 
     //wrap to ensure torroidal space 
     if (pos[l] < origin[l]) pos[l] += dims[l]; 
     if (pos[l] >= (origin[l] + dims[l])) pos[l] -= dims[l]; 

     parts->m_hPos[k * 4 + l] = pos[l]; 
    } 
} 

的問題是,當我以這種方式進行旋轉,與角度參數設置爲(0.0,0.0,1.0)它的工作原理(在某種程度上),但對象發生變形,像這樣:

alt text http://www.cs.nott.ac.uk/~jqs/squashed.png

這不是我想要的。任何人都可以告訴我我做錯了什麼,以及如何繞軸旋轉整個對象而不會使其變形?

感謝

nodlams

+1

你的輪換代碼看起來不錯。嘗試它沒有你的包裝代碼? – rlbond

+0

我剛試過,沒有換行代碼,很不幸,它沒有改變。 –

+1

我不確定...但在旋轉函數的第二個語句中(即pos [1] = ...),您正在使用pos [0]的更新值。這是打算嗎? – Ponting

回答

7

哪裏你做你的旋轉rotateByMatrix,你計算出新的POS [0],但隨後即飼料到下一行用於計算新的POS [1]。所以你用來計算新pos [1]的pos [0]不是輸入,而是輸出。將結果存儲在臨時變量中並返回。

Coord<float> tmp; 
tmp[0] = (cosf(zrot) * pos[0] - (sinf(zrot) * pos[1])); 
tmp[1] = (sinf(zrot) * pos[0] + cosf(zrot) * pos[1]); 
return tmp; 

另外,將pos作爲const引用傳入函數。

const Coord<float> &pos 

另外,您應該計算罪,一旦將CoS值,將其存儲在臨時變量並重新使用它們。

+0

啊,那是行得通的,我是新來的,我一定在某個地方犯了一個愚蠢的錯誤。謝謝你的幫助! –