问题
I am trying to learn 3d programming, and right now I am trying to understand how to use quaternions to rotate a vector around an axis.
As far as I understand, to rotate a vector v around an axis a, after converting both vectors to quaternions, we multiply v by a, then the product by the conjugate of a.
I want to rotate v(0,1,0) around a(1,0,0) by 90 degrees, and I should get a resulting vector v(0,0,1) (or 0,0,-1, depending on the direction of the rotation).
I am not getting the output I am expecting. Here is the code:
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;
}
and here is the output:
q not normalized, which is same as q normalized: x = 0.707107, y = 0, z = 0, w = 0.707107
r not normalized: x = 0.707107, y = 0, z = 1, w = -2.12132 r normalized: x = 0.288675, y = 0, z = 0.408248, w = -0.866025
what am I doing wrong? did I even understand anything from this process?
回答1:
Basically to rotate an vector along x axis (1,0,0) with angle 90 deg, use below method, this works for both Euler and quaternion
| 1 0 0 | | 0 | | 0 |
| 0 cos90 -sin90 | * | 1 | = | 0 |
| 0 sin90 cos90 | | 0 | | 1 |
Read about rotation matrices http://en.wikipedia.org/wiki/Rotation_matrix
来源:https://stackoverflow.com/questions/29779300/rotating-a-vector-around-an-axis-with-quaternion