Let's say I have 2 3D Vectors
Vec3 v1, v2;
v1.x = 203;
v1.y = 355;
v1.z = 922;
v2.x = 6;
v2.y = 13;
v2.z = 198;
How would I calculate the angle between v1
& v2
? I.e. the final answer would be within 0
to 360
I've tried
Vec3 angle = v1 - v2;
And a few other things but I just can't seem to get it working correctly.
You need to use the dot product for this, and once you have that you can follow the standard method. Example:
#include <cmath>
float dot(Vec3 a, Vec3 b) //calculates dot product of a and b
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
float mag(Vec3 a) //calculates magnitude of a
{
return std::sqrt(a.x * a.x + a.y * a.y + a.z * a.z);
}
int main()
{
Vec3 v1, v2;
v1.x = 203;
v1.y = 355;
v1.z = 922;
v2.x = 6;
v2.y = 13;
v2.z = 198;
float angle = std::acos(dot(v1,v2)/(mag(v1)*mag(v2)));
}