gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:39:16 25 4
gpt4 key购买 nike

我想将一个向量旋转到 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];

然而,结果r[4]并不是我所期望的。所以我认为我在上面的某些地方犯了一些错误。谁能给我一些提示?

最佳答案

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

  1. 规范化
  2. 取他们的点积得到旋转角度的余弦值
  3. 用他们的叉积找到一个正交旋转向量
  4. 以在#2 中找到的角度围绕新向量旋转

如果你还记得|,则可以省略第 2 步一个×乙 | = sin(theta) 如果 AB 都归一化。

关于opengl - 如何将矢量旋转到与 Z 轴对齐的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10798954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com