C++ 计算两个 3D 向量之间的角度(0 到 360)
C++ Calculate Angle (0 to 360) Between Two 3D Vectors
假设我有 2 个 3D 矢量
Vec3 v1, v2;
v1.x = 203;
v1.y = 355;
v1.z = 922;
v2.x = 6;
v2.y = 13;
v2.z = 198;
如何计算 v1
和 v2
之间的角度? IE。最终答案将在 0
到 360
之间
我试过了
Vec3 angle = v1 - v2;
还有其他一些东西,但我似乎无法让它正常工作。
您需要使用dot product for this, and once you have that you can follow the standard method。
示例:
#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)));
}
假设我有 2 个 3D 矢量
Vec3 v1, v2;
v1.x = 203;
v1.y = 355;
v1.z = 922;
v2.x = 6;
v2.y = 13;
v2.z = 198;
如何计算 v1
和 v2
之间的角度? IE。最终答案将在 0
到 360
我试过了
Vec3 angle = v1 - v2;
还有其他一些东西,但我似乎无法让它正常工作。
您需要使用dot product for this, and once you have that you can follow the standard method。 示例:
#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)));
}