2012-05-29 60 views
1

我想旋轉一個矢量到Z軸,它的方向是Z軸向後。所以如果向量是(1,1,1),我的結果應該是(0,0,-sqrt(3))。如何將矢量旋轉到與Z軸對齊的位置?

我的想法是兩個步驟。第一步是將我的矢量繞X軸旋轉到XZ平面。第二步是將XZ平面中的矢量繞Y軸旋轉到Z軸。

這是我的代碼:

GLfloat p[4] = {1,1,1,0}; //my vector, in homogeneous coordinates 
GLfloat r[4]; //result vector to test 

float theta1 = ((double)180/PI)*asin(p[1]/sqrt(p[0]*p[0]+p[1]*p[1]+p[2]*p[2])); 
//angle theta1 between the vector and XZ plane, is this right ??? I doubt it !!! 
float theta2 = ((double)180/PI)*atan(p[0]/p[2]); 
//angle theta2 between the vector's projection in XZ plane and Z axis 

GLfloat m[16]; 
glMatrixMode(GL_MODELVIEW); // get the rotation matrix in model-view matrix 
glPushMatrix(); 
glLoadIdentity(); 
glRotatef(theta1, 1,0,0); //rotate to the XZ plane 
glRotatef(180-theta2,0,1,0); //rotate to the Z axis 
glGetFloatv(GL_MODELVIEW_MATRIX, m); // m is column-major. 
glPopMatrix(); 

// use the matrix multiply my vector and get the result vector r[4] 
//my expectation is (0,0,-sqrt(3)) 
r[0] = p[0]*m[0]+p[1]*m[4]+p[2]*m[8]+p[3]*m[12]; 
r[1] = p[0]*m[1]+p[1]*m[5]+p[2]*m[9]+p[3]*m[13]; 
r[2] = p[0]*m[2]+p[1]*m[6]+p[2]*m[10]+p[3]*m[14]; 
r[3] = p[0]*m[3]+p[1]*m[7]+p[2]*m[11]+p[3]*m[15]; 

然而,結果r [4]是不我的期望。所以我想我在上面的一些地方犯了一些錯誤。任何人都可以給我一個暗示嗎?

+1

當然我誤解了這個問題。給定一個向量'v',你正在搜索'x =(0,0,-v.length())'?從你的問題:「到Z軸」 - >「x = y = 0」,「Z軸向後」意味着沿着Z軸的長度。 –

+0

Stefan Hanke:是的,這就是我的意思。 – TonyLic

回答

4

要旋轉一個向量,因此面臨着另一個問題:

  1. 正常化它
  2. 帶着點產品,以獲得旋轉角度
  3. 把他們的交叉產品的餘弦找到一個正交旋轉矢量
  4. 繞由角度新矢量在#2發現

步驟2可以,如果你可以省略如果AB都歸一化,請記住| A x B | = sin(theta)

+0

哦,你是着火了。你的回答正是我想要的!非常感謝你!!!! – TonyLic