pose2d.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. //
  2. // Created by zx on 22-12-1.
  3. //
  4. //
  5. // Created by zx on 2020/9/9.
  6. //
  7. #include "pose2d.h"
  8. Pose2d::Pose2d()
  9. :m_x(0),m_y(0),m_theta(0)
  10. {
  11. }
  12. Pose2d::Pose2d(float x,float y,float theta)
  13. :m_x(x),m_y(y),m_theta(theta)
  14. {
  15. }
  16. Pose2d::~Pose2d()
  17. {}
  18. std::ostream& operator<<(std::ostream &out,const Pose2d& point)
  19. {
  20. out<<"[x:"<<point.x()<<", y:"<<point.y()<<", theta:"<<point.theta()*180.0/M_PI<<"°]";
  21. return out;
  22. }
  23. const float Pose2d::gridient() const
  24. {
  25. double gradient=tanf(m_theta);
  26. if(fabs(gradient)>200)
  27. return 200.0*(gradient/fabs(gradient));
  28. return gradient;
  29. }
  30. float Pose2d::vector2yaw(float x,float y)
  31. {
  32. float r=sqrt(x*x+y*y);
  33. if(r<1e-8)
  34. return 0;
  35. float yaw=asin(y/r);
  36. if(x>=0) //1,4象限
  37. return yaw;
  38. if (x<0 ) //2 3象限
  39. return M_PI-yaw;
  40. }
  41. Pose2d Pose2d::relativePose(const Pose2d& target_pose,const Pose2d& axis_pose)
  42. {
  43. Pose2d diff=target_pose-axis_pose;
  44. Pose2d nPose=diff.rotate(-axis_pose.theta());
  45. float new_theta=diff.theta();
  46. //转换到 [-pi, pi]下
  47. int n=int(new_theta/(2*M_PI));
  48. if(new_theta<-M_PI)
  49. {
  50. new_theta += 2*M_PI*(n+1);
  51. }
  52. if(new_theta>M_PI)
  53. {
  54. new_theta -= 2*M_PI*(n+1);
  55. }
  56. return Pose2d(nPose.x(),nPose.y(),new_theta);
  57. }
  58. float Pose2d::distance(const Pose2d& pose1,const Pose2d& pose2)
  59. {
  60. Pose2d offset=pose1-pose2;
  61. return sqrt(offset.x()*offset.x()+offset.y()*offset.y());
  62. }
  63. Pose2d Pose2d::rotate(float theta)const
  64. {
  65. double cs=cos(theta);
  66. double sn=sin(theta);
  67. float x=cs*this->x()-sn*this->y();
  68. float y=sn*this->x()+cs*this->y();
  69. float new_theta=this->theta()+theta;
  70. if(theta<0)
  71. new_theta=new_theta+2*M_PI;
  72. if(new_theta>=2*M_PI)
  73. new_theta-=2*M_PI;
  74. if(new_theta>M_PI)
  75. new_theta=new_theta-2*M_PI;
  76. /*//转换到 [-pi/2, pi/2]下
  77. int n=int(new_theta/(M_PI));
  78. if(new_theta<-M_PI/2)
  79. {
  80. new_theta += M_PI*(n+1);
  81. }
  82. if(new_theta>M_PI/2)
  83. {
  84. new_theta -= M_PI*(n+1);
  85. }*/
  86. return Pose2d(x,y,new_theta);
  87. }
  88. Pose2d Pose2d::rotate(float ox,float oy,float theta)const{
  89. Pose2d translate(x()-ox,y()-oy,theta);//平移
  90. Pose2d rotated=rotate(theta);
  91. Pose2d ret(rotated.x()+x(),rotated.y()+y(),rotated.theta());
  92. return ret;
  93. }