Jump to content

Rotation Between Two Vectors


photo

Recommended Posts

Posted

Hi,

 

Also, is there a utility function that can return the rotation between two vectors?

 

vec3 a; // assuming unit vectors
vec3 b;
mat4 rot = ?;
b = a * rot;

 

 

On a side note, documentation is not particularly clear on that the setTo function does.

Can you explain?

 

 

 

Thanks

Posted

might do the trick

 

#include <unigine.h>

// assuming unit vectors
vec3 a; 
vec3 b;

vec3  axis  = cross( a, b );
float angle = acos( dot( a, b ) );

mat4 rot = mat4( axis, angle * RAD2DEG );

b = rot * a;

Posted

Thanks Ulf! Yeah, that's what I found online as the standard solution.

 

However, I did run in to some comments regarding the robustness of the solution when the two vectors are nearly aligned to each other in rotation already (maybe relating to the cross product or dot product being really small and losing precision?), or if the vectors are opposites (unavoidable). See Post #8

 

And, I was curious if Unigine provided a solution handling any special cases like that.

 

I did end up finding this bit of code in the utils.h

 

It seems that if you pass the cross product in as the up vector, you get the equivalent of the standard solution.

Or, leaving at default would be a rotation which maintains the up direction of the world, probably for things like a camera rotation where you don't want players getting dizzy :) (unless you do... lol)

 

float getAngle(vec3 v0,vec3 v1,vec3 up = vec3(0.0f,0.0f,1.0f)) {
vec3 c = cross(v0,v1);
float d = dot(c,up);
float a = atan2(length(c),dot(v0,v1));
return a * sign(d) * RAD2DEG;
}

 

I think I'll be fine using this for now, but it would be nice to have such a useful function be officially documented, and perhaps one that handles special cases, as well.

  • Like 1
×
×
  • Create New...