Original Post
I am trying to rotate an object toward a location in space. I have the math for rotating one vector towards another down just fine, and it all works. However, when I multiple the resulting rotation on to the matrix stack, the resulting rotation is not what I expected. The rotations come out as a left-handed rotation and what seems to be local rotations. The object is original facing the -z axis (0.0,0.0,-1.0). I rotate the object to face the positive y axis (0.0,1.0,0.0). The heading vector says its facing the positive y axis but the object ends up facing the -y axis. If I then rotate it to face the negative x axis the object ends up rotating around the y axis, but the heading vector ends up facing the correct position. Any help would be greatly appreciated. Create rotation to turn one vector into another Quaternion to matrix code What I do with the code above
// TODO: needs optimizing
quaternion::quaternion(const vec3d& from, const vec3d& to)
{
vec3d current = from;
vec3d target = to;
target.normalize();
current.normalize();
double angle = acos( current.dot(target) ) * TO_DEGREES;
vec3d axis = current.cross(target);
if ( fabs(angle) <= 0.00001)
{
*this = quaternion();
return;
}
if ( fabs(angle -180.0) <= 0.00001 )
{
vec3d temp;
if( fabs(from.i) < fabs(from.j) )
{
if( fabs(from.i) < fabs(from.k) )
temp.set(1.0,0.0,0.0);
else
temp.set(0.0,0.0,1.0);
}
else if( fabs( from.j) < fabs(from.k) )
temp.set(0.0,1.0,0.0);
else
temp.set(0.0,0.0,1.0);
axis = from.cross(temp);
}
*this = quaternion(angle,axis);
}
matrix quaternion::toMatrix() const
{
matrix _matrix;
// Pre-compute quat combinations
double xw = _quat[1]*_quat[0],
xx = _quat[1]*_quat[1],
xy = _quat[1]*_quat[2],
xz = _quat[1]*_quat[3],
yw = _quat[2]*_quat[0],
yy = _quat[2]*_quat[2],
yz = _quat[2]*_quat[3],
zw = _quat[3]*_quat[0],
zz = _quat[3]*_quat[3];
// Apply quat combinations
_matrix[0] = 1.0-2.0*(yy + zz);
_matrix[1] = 2.0*(xy - zw);
_matrix[2] = 2.0*(xz + yw);
_matrix[3] = 0.0;
_matrix[4] = 2.0*(xy + zw);
_matrix[5] = 1.0-2.0*(xx + zz);
_matrix[6] = 2.0*(yz - xw);
_matrix[7] = 0.0;
_matrix[8] = 2.0*(xz - yw);
_matrix[9] = 2.0*(yz + xw);
_matrix[10] =1.0 -2.0*(xx + yy);
_matrix[11] = 0.0;
_matrix[12] = 0.0;
_matrix[13] = 0.0;
_matrix[14] = 0.0;
_matrix[15] = 1.0;
return _matrix;
}
_rotation = quaternion(heading,target) * _rotation;
glPushMatrix();
glMultMatrixd( _rotation.toMatrix() );
glPopMatrix();