Get the directional rotation angle between 2 vectors


/ Published in: C++
Save to your folder(s)



Copy this code and paste it in your HTML
  1. struct Vector
  2. {
  3. double x, y;
  4. };
  5.  
  6.  
  7. double getRotateAngle(Vector vec1, Vector vec2)
  8. {
  9. const double epsilon = 1.0e-6;
  10. const double PI = acos(-1.0); // 180 degree
  11. double angle = 0;
  12.  
  13. // normalize
  14. Vector norVec1, norVec2;
  15. norVec1.x = vec1.x / sqrt(pow(vec1.x, 2) + pow(vec1.y, 2));
  16. norVec1.y = vec1.y / sqrt(pow(vec1.x, 2) + pow(vec1.y, 2));
  17. norVec2.x = vec2.x / sqrt(pow(vec2.x, 2) + pow(vec2.y, 2));
  18. norVec2.y = vec2.y / sqrt(pow(vec2.x, 2) + pow(vec2.y, 2));
  19.  
  20. // dot product
  21. double dotProd = (norVec1.x * norVec2.x) + (norVec1.y * norVec2.y);
  22. if ( abs(dotProd - 1.0) <= epsilon )
  23. angle = 0;
  24. else if ( abs(dotProd + 1.0) <= epsilon )
  25. angle = PI;
  26. else {
  27. double cross = 0;
  28. angle = acos(dotProd);
  29. //cross product (clockwise or counter-clockwise)
  30. cross = (norVec1.x * norVec2.y) - (norVec2.x * norVec1.y);
  31.  
  32. if (cross < 0) // vec1 rotate clockwise to vec2
  33. angle = 2 * PI - angle;
  34. }
  35.  
  36. return angle*(180 / PI);
  37.  
  38. }

URL: http://www.cnblogs.com/lsmdiao0812/archive/2010/05/05/1728122.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.