pose2d.cpp 2.2 KB

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