3D矢量的角度 - 得到两者

时间:2013-03-22 22:37:51

标签: c++ 3d game-physics

我有速度对象A.速度指定为3D矢量a = (x, y, z)。位置是3D点A [X, Y, Z]。我需要找出,如果当前速度将此对象引导到位置B [X, Y, Z]上的另一个对象B. 我已成功实现了2个维度,忽略了第三个维度:

   /*A is projectile, B is static object*/
    //entity is object A
    //  - .v[3] is the speed vector
    //position[3] is array of coordinates of object B    


    double vector[3];                               //This is the vector c = A-B
    this->entityVector(-1, entity.id, vector);      //Fills the correct data
    double distance = vector_size(vector);          //This is distance |AB|
    double speed = vector_size(entity.v);      //This is size of speed vector a

    float dist_angle = (float)atan2(vector[2],vector[0])*(180.0/M_PI);           //Get angle of vector c as seen from Y axis - using X, Z
    float speed_angle = (float)atan2((double)entity.v[2],entity.v[0])*(180.0/M_PI); //Get angle of vector a seen from Y axis - using X, Z
    dist_angle = deg180to360(dist_angle);             //Converts value to 0-360
    speed_angle = deg180to360(speed_angle);           //Converts value to 0-360
    int diff = abs((int)compare_degrees(dist_angle, speed_angle));   //Returns the difference of vectors direction

我需要创建相同的比较以使其在3D中工作 - 现在,忽略Y位置和Y矢量坐标。
我应该采取什么计算来获得第二个角度?

根据回答

编辑
我正在使用球面坐标并比较它们的角度来检查两个矢量是否指向同一方向。当一个向量是A-B和另一个A的速度时,我检查ID A是否朝向B.

1 个答案:

答案 0 :(得分:5)

我假设您正在寻找的“第二个角度”是φ。也就是说,你使用的是球坐标:

(x,y,z) => (r,θ,φ)
r = sqrt(x^2 + y^2 + z^2)
θ = cos^-1(z/r)
φ = tan^-1(y/x)

但是,如果您要做的就是找到A是否以速度a向B移动,您可以使用点积作为基本答案。

1st vector: B - A (vector pointing from A to B)
2nd vector: a (velocity)
dot product: a * (B-A)

如果点积为0,则意味着你没有接近 - 你正在一个半径恒定的球体上移动|| B-A ||以B为中心。如果点积> 0,你正朝着这个点移动,如果点积< 0,你正在远离它。