pose2d.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 ) //2 3象限
  37. yaw= M_PI-yaw;
  38. if(yaw>M_PI)
  39. yaw-=M_PI*2;
  40. if(yaw<=-M_PI)
  41. yaw+=M_PI*2;
  42. return yaw;
  43. }
  44. Pose2d Pose2d::relativePose(const Pose2d& target_pose,const Pose2d& axis_pose)
  45. {
  46. Pose2d diff=target_pose-axis_pose;
  47. Pose2d nPose=diff.rotate(-axis_pose.theta());
  48. float new_theta=diff.theta();
  49. //转换到 [-pi, pi]下
  50. int n=int(new_theta/(2*M_PI));
  51. if(new_theta<-M_PI)
  52. {
  53. new_theta += 2*M_PI*(n+1);
  54. }
  55. if(new_theta>M_PI)
  56. {
  57. new_theta -= 2*M_PI*(n+1);
  58. }
  59. return Pose2d(nPose.x(),nPose.y(),new_theta);
  60. }
  61. float Pose2d::distance(const Pose2d& pose1,const Pose2d& pose2)
  62. {
  63. Pose2d offset=pose1-pose2;
  64. return sqrt(offset.x()*offset.x()+offset.y()*offset.y());
  65. }
  66. Pose2d Pose2d::rotate(float theta)const
  67. {
  68. double cs=cos(theta);
  69. double sn=sin(theta);
  70. float x=cs*this->x()-sn*this->y();
  71. float y=sn*this->x()+cs*this->y();
  72. float new_theta=this->theta()+theta;
  73. if(theta<=-M_PI)
  74. new_theta=new_theta+2*M_PI;
  75. if(new_theta>M_PI)
  76. new_theta-=2*M_PI;
  77. return Pose2d(x,y,new_theta);
  78. }
  79. Pose2d Pose2d::rotate(float ox,float oy,float theta)const{
  80. Pose2d translate(x()-ox,y()-oy,m_theta);//平移
  81. Pose2d rotated=translate.rotate(theta);
  82. Pose2d ret(rotated.x()+x(),rotated.y()+y(),rotated.theta());
  83. return ret;
  84. }