roscd learning_tf
新建文件turtle_tf_listener.cpp
#include <ros/ros.h>
#include <tf/transform_listener.h>
#include <geometry_msgs/Twist.h>
#include <turtlesim/Spawn.h>
int main(int argc, char** argv){
ros::init(argc, argv, "my_tf_listener");
ros::NodeHandle node;
ros::service::waitForService("spawn");
ros::ServiceClient add_turtle =
node.serviceClient<turtlesim::Spawn>("spawn");
turtlesim::Spawn srv;
add_turtle.call(srv);
ros::Publisher turtle_vel =
node.advertise<geometry_msgs::Twist>("turtle2/cmd_vel", 10);
tf::TransformListener listener;
ros::Rate rate(10.0);
while (node.ok()){
tf::StampedTransform transform;
try{
listener.lookupTransform("/turtle2", "/turtle1",
ros::Time(0), transform);
}
catch (tf::TransformException &ex) {
ROS_ERROR("%s",ex.what());
ros::Duration(1.0).sleep();
}
geometry_msgs::Twist vel_msg;
vel_msg.angular.z = 4.0 * atan2(transform.getOrigin().y(),
transform.getOrigin().x());
vel_msg.linear.x = 0.5 * sqrt(pow(transform.getOrigin().x(), 2) +
pow(transform.getOrigin().y(), 2));
turtle_vel.publish(vel_msg);
rate.sleep();
}
return 0;
};
代码解释
#include <tf/transform_listener.h>
tf包提供了一个实现机制TransformListener来帮助更容易实现接收转换,为了要使用这个TransformListener,就要包含tf包中的tansform_listener.h头文件
tf::TransformListener listener;
在这里我们创建了一个TransformListener名称为listener,一旦listener创建后,它开始就接收tf的转换消息并让它们缓冲10s.TransformListener应该要一直存在,否则它的缓存将不能填满并且几乎所有的查询将不能进行
try{
listener.lookupTransform("/turtle2", "/turtle1",
ros::Time(0), transform);
}
我们查询listener为一个指定的转换,有四个主要参数:
1,2我们想要转换从turtle2到turtle1,也即最初运行结果所看到的当turtle2移动时,turtle1跟随着turtle2的轨迹移动
3转换的时间
4用transform来存储转换结果
geometry_msgs::Twist vel_msg;
vel_msg.angular.z = 4.0 * atan2(transform.getOrigin().y(),
transform.getOrigin().x());
vel_msg.linear.x = 0.5 * sqrt(pow(transform.getOrigin().x(), 2) +
pow(transform.getOrigin().y(), 2));
transform用来计算新的线性和角度的向量值为turtle2,这是基于turtle2到turtle1的距离和角度,新的向量值将会发布在主题turtle2/cmd_vel上,sim乌龟将会使用它并更改turtle2的移动
打开 CMakeLists.txt,并且进行编译。
add_executable(turtle_tf_listener src/turtle_tf_listener.cpp)
target_link_libraries(turtle_tf_listener ${catkin_LIBRARIES})
修改 start_demo.launch中的内容。
<launch>
<!-- Turtlesim Node-->
<node pkg="turtlesim" type="turtlesim_node" name="sim"/>
<node pkg="turtlesim" type="turtle_teleop_key" name="teleop" output="screen"/>
<!-- Axes -->
<param name="scale_linear" value="2" type="double"/>
<param name="scale_angular" value="2" type="double"/>
<node pkg="learning_tf" type="turtle_tf_broadcaster"
args="/turtle1" name="turtle1_tf_broadcaster" />
<node pkg="learning_tf" type="turtle_tf_broadcaster"
args="/turtle2" name="turtle2_tf_broadcaster" />
<node pkg="learning_tf" type="turtle_tf_listener"
name="listener" />
</launch>
roslaunch learning_tf start_demo.launch
turtle2会跟随turtle1运行。