1 建立自己的工作站
mkdir -p ~/catkin_ws/src
cd ~/catkin_ws/
catkin_make
2 创建ros包
cd ~/catkin_ws/src
catkin_create_pkg my_gazebo_models rospy gazebo_ros
3创建自己的scripts 所有py文件放在这里
cd ~/catkin_ws/src/my_gazebo_models
mkdir scripts
cd scripts
touch spawn_model.py
chmod +x spawn_model.py
4 启动 你的py代码
注意roscore为一个terminal和后面的roslaunch、chmod、source为一个terminal、rosrun为一个terminal
roscore# 启动ros
roslaunch gazebo_ros empty_world.launch #启动一个空的世界
chmod +x ~/catkin_ws/src/my_gazebo_models/scripts/spawn_model.py
source ~/catkin_ws/devel/setup.bash #配置源,如果你不是bash,把bash换成zsh
rosrun my_gazebo_models spawn_model.py#启动你的py代码,解释一下my_gazebo_models这个实质是你配置的ros包名字,spawn_model.py 这个是你的py代码
5你可能遇到的问题:
1 py代码把这两行放在最前面
#!/usr/bin/env python
-*- coding: utf-8 -*-
2 遇到这样的问题:
Traceback (most recent call last):
File "/home/asic/catkin_ws/src/my_gazebo_models/scripts/spawn_model.py", line 4, in <module>
import rospy
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/__init__.py", line 47, in <module>
from std_msgs.msg import Header
File "/opt/ros/noetic/lib/python3/dist-packages/std_msgs/msg/__init__.py", line 1, in <module>
from ._Bool import *
File "/opt/ros/noetic/lib/python3/dist-packages/std_msgs/msg/_Bool.py", line 6, in <module>
import genpy
File "/opt/ros/noetic/lib/python3/dist-packages/genpy/__init__.py", line 34, in <module>
from . message import Message, SerializationError, DeserializationError, MessageException, struct_I
File "/opt/ros/noetic/lib/python3/dist-packages/genpy/message.py", line 48, in <module>
import yaml
ImportError: No module named yaml
pyyaml包没有引入
pip3 install pyyaml 下载pyyaml包
python3 -m pip show pyyaml 查看是否下载完成
生成指定位置的障碍物
需要进行一些修改,如你的模型路径、名称等,这是一定要修改的
#!/usr/bin/env python3
-*- coding: utf-8 -*-
#必须添加以上两行
import sys
import os
sys.path.append('/usr/lib/python3/dist-packages')#手动添加路径
print("PYTHONPATH:", os.environ.get('PYTHONPATH'))
print("sys.path:", sys.path)
import rospy
from gazebo_msgs.srv import SpawnModel
from geometry_msgs.msg import Pose, Point, Quaternion
def load_model(model_path):
with open(model_path, 'r') as model_file:
model_xml = model_file.read()
return model_xml
def spawn_model(model_name, model_xml, pose, reference_frame="world"):
rospy.wait_for_service('/gazebo/spawn_sdf_model')
try:
spawn_model_prox = rospy.ServiceProxy('/gazebo/spawn_sdf_model', SpawnModel)
spawn_model_prox(model_name, model_xml, "", pose, reference_frame)
rospy.loginfo("Model {} spawned successfully".format(model_name))
except rospy.ServiceException as e:
rospy.logerr("Service call failed: {}".format(e))
if name == "__main__":
rospy.init_node('spawn_model_node')
model_name = "cafe_table"
model_path = "/home/asic/.gazebo/models/cafe_table/model.sdf"
model_xml = load_model(model_path)
pose = Pose()
pose.position = Point(x=1, y=2, z=0) # 修改为你需要的位置
pose.orientation = Quaternion(x=0, y=0, z=0, w=1)
spawn_model(model_name, model_xml, pose)
可以定向移动的障碍物
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
import time
import rospy
from gazebo_msgs.srv import SpawnModel, DeleteModel, SetModelState
from gazebo_msgs.msg import ModelState
from geometry_msgs.msg import Pose, Point, Quaternion
def load_model(model_path):
with open(model_path, 'r') as model_file:
model_xml = model_file.read()
return model_xml
def spawn_model(model_name, model_xml, pose, reference_frame="world"):
rospy.wait_for_service('/gazebo/spawn_sdf_model')
try:
spawn_model_prox = rospy.ServiceProxy('/gazebo/spawn_sdf_model', SpawnModel)
spawn_model_prox(model_name, model_xml, "", pose, reference_frame)
rospy.loginfo("Model {} spawned successfully".format(model_name))
except rospy.ServiceException as e:
rospy.logerr("Service call failed: {}".format(e))
def delete_model(model_name):
rospy.wait_for_service('/gazebo/delete_model')
try:
delete_model_prox = rospy.ServiceProxy('/gazebo/delete_model', DeleteModel)
delete_model_prox(model_name)
rospy.loginfo("Model {} deleted successfully".format(model_name))
except rospy.ServiceException as e:
rospy.logerr("Service call failed: {}".format(e))
def set_model_state(model_name, pose):
rospy.wait_for_service('/gazebo/set_model_state')
try:
set_model_state_prox = rospy.ServiceProxy('/gazebo/set_model_state', SetModelState)
model_state = ModelState()
model_state.model_name = model_name
model_state.pose = pose
set_model_state_prox(model_state)
rospy.loginfo("Model {} moved to new position".format(model_name))
except rospy.ServiceException as e:
rospy.logerr("Service call failed: {}".format(e))
if __name__ == "__main__":
rospy.init_node('move_model_node')
model_name = "cafe_table"
model_path = "/home/asic/.gazebo/models/cafe_table/model.sdf"
model_xml = load_model(model_path)
# 初始位置和姿态
start_pose = Pose()
start_pose.position = Point(x=1, y=2, z=0)
start_pose.orientation = Quaternion(x=0, y=0, z=0, w=1)
end_pose = Pose()
end_pose.position = Point(x=3, y=2, z=0)
end_pose.orientation = Quaternion(x=0, y=0, z=0, w=1)
# 生成模型
spawn_model(model_name, model_xml, start_pose)
# 在两点之间来回移动
rate = rospy.Rate(1) # 1 Hz
direction = 1
current_pose = start_pose
while not rospy.is_shutdown():
if direction == 1:
current_pose.position.x += 0.1
if current_pose.position.x >= end_pose.position.x:
direction = -1
else:
current_pose.position.x -= 0.1
if current_pose.position.x <= start_pose.position.x:
direction = 1
set_model_state(model_name, current_pose)
rate.sleep()
# 删除模型
delete_model(model_name)
随机生成的障碍物
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
import time
import rospy
import random #随机
from gazebo_msgs.srv import SpawnModel, DeleteModel
from gazebo_msgs.msg import ModelState
from geometry_msgs.msg import Pose, Point, Quaternion
def load_model(model_path):
with open(model_path, 'r') as model_file:
model_xml = model_file.read()
return model_xml
def spawn_model(model_name, model_xml, pose, reference_frame="world"):
rospy.wait_for_service('/gazebo/spawn_sdf_model')
try:
spawn_model_prox = rospy.ServiceProxy('/gazebo/spawn_sdf_model', SpawnModel)
spawn_model_prox(model_name, model_xml, "", pose, reference_frame)
rospy.loginfo("Model {} spawned successfully".format(model_name))
except rospy.ServiceException as e:
rospy.logerr("Service call failed: {}".format(e))
def delete_model(model_name):
rospy.wait_for_service('/gazebo/delete_model')
try:
delete_model_prox = rospy.ServiceProxy('/gazebo/delete_model', DeleteModel)
delete_model_prox(model_name)
rospy.loginfo("Model {} deleted successfully".format(model_name))
except rospy.ServiceException as e:
rospy.logerr("Service call failed: {}".format(e))
if __name__ == "__main__":
rospy.init_node('spawn_random_models_node')
model_name_prefix = "cafe_table_"
model_path = "/home/asic/.gazebo/models/cafe_table/model.sdf"
model_xml = load_model(model_path)
num_models = 10
# 地图边界定义(
x_min, x_max = -10, 10
y_min, y_max = -10, 10
# 生成随机位置并生成模型
for i in range(num_models):
model_name = model_name_prefix + str(i)
pose = Pose()
pose.position = Point(
x=random.uniform(x_min, x_max),
y=random.uniform(y_min, y_max),
z=0
)
pose.orientation = Quaternion(x=0, y=0, z=0, w=1)
spawn_model(model_name, model_xml, pose)
for i in range(num_models):
model_name = model_name_prefix + str(i)
delete_model(model_name)