Calculate direction angle from two vectors?

后端 未结 4 913
时光说笑
时光说笑 2021-02-03 10:13

Say I have two 2D vectors, one for an objects current position and one for that objects previous position. How can I work out the angular direction of travel?

This image

4条回答
  •  星月不相逢
    2021-02-03 10:50

    Be careful to use atan2 to avoid quadrant issues and division by zero. That's what it's there for.

    float getAngle(CGPoint ptA, CGPoint ptOrigin, CGPoint ptB)
    {
        CGPoint A = makeVec(ptOrigin, ptA);
        CGPoint B = makeVec(ptOrigin, ptB);
    
        // angle with +ve x-axis, in the range (−π, π]
        float thetaA = atan2(A.x, A.y);  
        float thetaB = atan2(B.x, B.y);
    
        float thetaAB = thetaB - thetaA;
    
        // get in range (−π, π]
        while (thetaAB <= - M_PI)
            thetaAB += 2 * M_PI;
    
        while (thetaAB > M_PI)
            thetaAB -= 2 * M_PI;
    
        return thetaAB;
    }
    

    However, if you don't care about whether it's a +ve or -ve angle, just use the dot product rule (less CPU load):

    float dotProduct(CGPoint p1, CGPoint p2) { return p1.x * p2.x + p1.y * p2.y; }
    
    float getAngle(CGPoint A, CGPoint O, CGPoint B)
    {
        CGPoint U = makeVec(O, A);
        CGPoint V = makeVec(O, B);
    
        float magU = vecGetMag(U);
        float magV = vecGetMag(V);
        float magUmagV = magU * magV;   assert (ABS(magUmagV) > 0.00001);
    
        // U.V = |U| |V| cos t
        float cosT = dotProduct(U, V) / magUmagV;
        float theta = acos(cosT);
        return theta;
    }
    

    Note that in either code section above, if one ( or both ) vectors are close to 0 length this is going to fail. So you might want to trap that somehow.

提交回复
热议问题