如何将向量旋转到与Z轴对齐的位置?

Ton*_*Lic 1 opengl rotatetransform rotation matrix

我想将向量旋转到Z轴,并且其方向是Z轴向后。因此,如果向量为(1,1,1),则我的结果应为(0,0,-sqrt(3))。

我的想法是两个步骤。第一步是将我的向量绕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]; 
Run Code Online (Sandbox Code Playgroud)

但是,结果r [4]不是我的期望。所以我想我在上面的某些地方犯了一些错误。有人可以给我提示吗?

Aln*_*tak 5

旋转一个向量使其面向另一个向量:

  1. 归一化
  2. 取他们的点积以获得旋转角的余弦
  3. 取叉积找到正交旋转向量
  4. 围绕新矢量旋转#2中找到的角度

如果您记得将和都标准化,| A x B | = sin(theta)则可以省略第2步。AB