Calculate direction angle from two vectors?

后端 未结 4 916
时光说笑
时光说笑 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 11:03

    Still not sure what you mean by rotation matrices, but this is a simple case of getting an azimuth from a direction vector.

    The complicated answer:

    Normally you should pack a few conversion/utility functions with your 2D vectors: one to convert from X,Y (carthesian) to Theta,R (polar coordinates). You should also support basic vector operations like addition, substraction and dot product. Your answer in this case would be:

     double azimuth  =  (P2 - P1).ToPolarCoordinate().Azimuth;
    

    Where ToPolarCoordinate() and ToCarhtesianCoordinate() are two reciprocal functions switching from one type of vector to another.

    The simple one:

     double azimuth = acos ((x2-x1)/sqrt((x2-x1) * (x2-x1) + (y2-y1) * (y2-y1));
     //then do a quadrant resolution based on the +/- sign of (y2-y1) and (x2-x1)
     if (x2-x1)>0 {
       if (y2-y1)<0 {  azimuth = Pi-azimuth; } //quadrant 2
     } else 
     { if (y2-y1)> 0 {  azimuth = 2*Pi-azimuth;} //quadrant 4
        else  { azimuth = Pi + azimuth;} //quadrant 3
     }
    

提交回复
热议问题