Quaternion describing direction

Started by
1 comment, last by MAB 12 years, 7 months ago
Hello,

I have the following problem:
I have two points (x1,y1,z1) and (x2,y2,z2)
And i need to calculate quaternion describing vector from first to second point.

Thanks in advance.

Best regards.
Advertisement
Unless (x1,y1,z1) and (x2,y2,z2) have the same length, the problem cannot be solved, since applying quaternions to vectors only rotates them around the origin, and cannot translate (or scale them w.r.to origin) them. This is the code I use:



/// Creates a new quaternion that rotates sourceDirection vector (in world space) to coincide with the
/// targetDirection vector (in world space).
/// Rotation is performed around the origin.
/// The vectors sourceDirection and targetDirection are assumed to be normalized.
/// @note There are multiple such rotations - this function returns the rotation that has the shortest angle
/// (when decomposed to axis-angle notation).
Quat Quat::RotateFromTo(const float3 &sourceDirection, const float3 &targetDirection)
{
assume(sourceDirection.IsNormalized());
assume(targetDirection.IsNormalized());
float angle = sourceDirection.AngleBetween(targetDirection);
assume(angle >= 0.f);
// If sourceDirection == targetDirection, the cross product comes out zero, and normalization would fail. In that case, pick an arbitrary axis.
float3 axis = sourceDirection.Cross(targetDirection);
float oldLength = axis.Normalize();
if (oldLength == 0)
axis = float3(1, 0, 0);
return Quat(axis, angle);
}




Thank you. :-)

This topic is closed to new replies.

Advertisement