我正在尝试学习 3d 编程,现在我正在尝试了解如何使用四元数围绕轴旋转 vector 。
据我所知,要围绕轴 a 旋转 vector v,在将两个 vector 转换为四元数后,我们将 v 乘以 a,然后乘以 a 的共轭。
我想将 v(0,1,0) 围绕 a(1,0,0) 旋转 90 度,我应该得到一个结果 vector v(0,0,1)(或 0,0,- 1,取决于旋转方向)。
我没有得到我期望的输出。 这是代码:
int main()
{
//I want to rotate this vector about the x axis by PI/2 radians:
Quaternion v(0, 1, 0, 0);
v.normalize();
float angle = PI / 2.0f;
float cos = math::cos(angle / 2.0f);
float sin = math::sin(angle / 2.0f);
Quaternion q(1.0f*sin, 0.0f*sin, 0.0f*sin, cos);
std::cout << "q not normalized = " <<"\t"<< q.x << " " << q.y << " " << q.z << " " << q.w << std::endl;
q.normalize();
std::cout << "q normalized = " <<"\t\t"<< q.x << " " << q.y << " " << q.z << " " << q.w << std::endl;
std::cout << std::endl;
Quaternion r;
//I multiply the vector v by the quaternion v, then I multiply by the conjugate.
r = q * v;
//do I need to normalize here?
r = r * q.conjugate();
//and here?
//shouldn't the resulting vector be 0,0,1?
std::cout << "r not normalized = " << "\t" << r.x << " " << r.y << " " << r.z << " " << r.w << std::endl;
r.normalize();
std::cout << "r normalized = " << "\t\t" << r.x << " " << r.y << " " << r.z << " " << r.w << std::endl;
std::cout << std::endl;
system("pause");
return 0;
}
这是输出:
q 未归一化,与 q 归一化相同: x = 0.707107, y = 0, z = 0, w = 0.707107
r 未归一化: x = 0.707107,y = 0,z = 1,w = -2.12132 标准化: x = 0.288675, y = 0, z = 0.408248, w = -0.866025
我做错了什么? 我什至从这个过程中了解了什么?
最佳答案
基本上要沿 x 轴 (1,0,0) 旋转一个 vector 90 度,使用下面的方法,这对欧拉和四元数都有效
| 1 0 0 | | 0 | | 0 |
| 0 cos90 -sin90 | * | 1 | = | 0 |
| 0 sin90 cos90 | | 0 | | 1 |
关于c++ - 使用四元数围绕轴旋转 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29779300/