Skip to content

Instantly share code, notes, and snippets.

@FantasyVR
Last active June 18, 2017 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FantasyVR/16724bfee3b6aa2fad11d8221c268c7f to your computer and use it in GitHub Desktop.
Save FantasyVR/16724bfee3b6aa2fad11d8221c268c7f to your computer and use it in GitHub Desktop.
Two vectors A and B. how to get a quaternion representing the rotation from A to B?
Template typename<T>
struct quaternion{
T w,x,y,z;
};
struct _vec3{
T x,y,z;
};
typedef quaternion quat ;
typedef _vec3 vec3;
quat FromTwoVector(vec3 A, vec3 B)
{
vec3 delta = (A - B).normalize();
float dot = dot( A, B);
vec3 half = (A + B).normalize();
quat dq;
if(dot>=1.0f) dq = quat(1,0.0,0.0,0.0);//that means A = B that is colinear but diffient direction,
else if(dot <1e-6f - 1.0f)
{
// that means two vector A = - B, colinear but diffient direction
float c = dot(A, vec3(1, 0, 0));
if (c < 1e-6f - 1.0f)
{
dq = quat(0,cross(A, vec3(0, 1, 0)));
}
dq = quat(0,cross(A, vec3(1, 0, 0)));
}
else
{
dq = quat(dot(from, half), cross(from, half));
}
}
@FantasyVR
Copy link
Author

Two vectors from and to. how to get a quaternion representing the rotation from A to B?
Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment