datetime:2025/12/21 16:00
author:nzb

为对象配置行为

本节内容

  • 为对象配置行为
    • 行为配置参数
    • 自定义行为的高级配置

Python 脚本与 YAML 配置文件

import irsim

env = irsim.make()
# load_behavior 函数会从 Python 脚本中加载自定义行为方法。custom_behavior_methods 是包含自定义行为函数的脚本名称。
# 请将名为 custom_behavior_methods 的脚本与主 Python 脚本放在同一目录下。
env.load_behavior("custom_behavior_methods")

for i in range(1000):

    env.step()
    env.render(0.05)

    if env.done():
        break

env.end()
from irsim.lib import register_behavior
from irsim.util.util import relative_position, WrapToPi
import numpy as np

# 必须使用 @register_behavior 装饰器注册自定义行为。装饰器的第一个参数为机动学名称(diff、acker、omni),第二个参数为在 YAML 中引用的行为名称。


@register_behavior("diff", "dash_custom")
def beh_diff_dash(ego_object, objects=[], **kwargs):
    """
    ego_object 表示需要控制的对象,objects 是仿真中的对象列表。自定义行为函数需返回对象的速度,并可从对象中获取状态、目标等属性。
    """
    state = ego_object.state
    goal = ego_object.goal
    goal_threshold = ego_object.goal_threshold
    _, max_vel = ego_object.get_vel_range()
    angle_tolerance = kwargs.get("angle_tolerance", 0.1)

    behavior_vel = DiffDash2(state, goal, max_vel, goal_threshold, angle_tolerance)

    return behavior_vel


def DiffDash2(state, goal, max_vel, goal_threshold=0.1, angle_tolerance=0.2):
    """一个计算冲刺速度的自定义行为函数"""
    distance, radian = relative_position(state, goal)

    if distance < goal_threshold:
        return np.zeros((2, 1))

    diff_radian = WrapToPi(radian - state[2, 0])
    linear = max_vel[0, 0] * np.cos(diff_radian)

    if abs(diff_radian) < angle_tolerance:
        angular = 0
    else:
        angular = max_vel[1, 0] * np.sign(diff_radian)

    return np.array([[linear], [angular]])
world:
  height: 10  # the height of the world
  width: 10   # the width of the world

robot:
  - number: 10
    distribution: {name: 'circle', radius: 4.0, center: [5, 5]}  
    kinematics: {name: 'diff'}
    shape: 
      - {name: 'circle', radius: 0.2} 
    # factor: 碰撞惩罚权重(默认 1.0,越大越保守)
    # behavior: {name: 'rvo', vxmax: 1.5, vymax: 1.5, acce: 1.0, factor: 1.0}
    behavior: {name: 'dash_custom'}
    vel_min: [-3, -3.0]
    vel_max: [3, 3.0]
    color: ['royalblue', 'red', 'green', 'orange', 'purple', 'yellow', 'cyan', 'magenta', 'lime', 'pink', 'brown'] 
    arrive_mode: position
    goal_threshold: 0.15
    plot:
      show_trail: true
      show_goal: true
      trail_fill: true
      trail_alpha: 0.2
      show_trajectory: false

results matching ""

    No results matching ""