pose2d.cpp 2.2 KB

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