如何在AnyLogic中获取行人/智能体前往的目标targetline数据
实现逻辑
你可以通过预存targetline配置、逐帧读取行人导航终点、做ID/空间匹配的方式拿到每位行人当前朝向的targetline信息,不需要修改PedSource的生成逻辑。
核心步骤:
- 初始化阶段缓存4条targetline的ID、端点坐标、匹配容差范围,存为字典结构方便快速查询
- 仿真循环中逐帧获取所有PedSource生成的行人实体,读取每个行人当前的导航终点ID或坐标
- 优先通过ID匹配对应targetline,无可用ID时用点到线段的距离做空间匹配,即可得到对应结果
参考代码
import math # 替换为你实际配置的4条targetline参数,match_range为空间匹配的容差距离 TARGET_LINE_INFO = { "targetline_1": {"tl_id": "tl_001", "start_pos": (10.2, 5.1), "end_pos": (22.3, 5.2), "match_range": 2.0}, "targetline_2": {"tl_id": "tl_002", "start_pos": (22.3, 5.2), "end_pos": (22.5, 20.7), "match_range": 2.0}, "targetline_3": {"tl_id": "tl_003", "start_pos": (22.5, 20.7), "end_pos": (10.1, 20.6), "match_range": 2.0}, "targetline_4": {"tl_id": "tl_004", "start_pos": (10.1, 20.6), "end_pos": (10.2, 5.1), "match_range": 2.0}, } def fetch_ped_current_target(ped_obj): """输入单个行人实体,返回其当前朝向的targetline信息,无匹配结果返回None""" # 以下两个方法替换为你所用仿真平台的对应接口 dest_edge_id = ped_obj.get_nav_target_id() dest_x, dest_y = ped_obj.get_nav_target_pos() # 优先走ID匹配,效率和准确率更高 for tl_name, tl_conf in TARGET_LINE_INFO.items(): if tl_conf["tl_id"] == dest_edge_id: return { "ped_id": ped_obj.entity_id, "matched_targetline": tl_name, "targetline_detail": tl_conf } # 无有效ID时走空间距离匹配 min_match_dist = float("inf") matched_result = None for tl_name, tl_conf in TARGET_LINE_INFO.items(): x1, y1 = tl_conf["start_pos"] x2, y2 = tl_conf["end_pos"] line_length = math.hypot(x2 - x1, y2 - y1) # 处理targetline长度为0的异常情况 if line_length == 0: point_dist = math.hypot(dest_x - x1, dest_y - y1) else: # 计算点到线段的垂直距离 proj_param = max(0, min(1, ((dest_x - x1) * (x2 - x1) + (dest_y - y1) * (y2 - y1)) / (line_length ** 2))) proj_x = x1 + proj_param * (x2 - x1) proj_y = y1 + proj_param * (y2 - y1) point_dist = math.hypot(dest_x - proj_x, dest_y - proj_y) # 容差范围内取距离最近的targetline if point_dist < tl_conf["match_range"] and point_dist < min_match_dist: min_match_dist = point_dist matched_result = (tl_name, tl_conf) if matched_result: return { "ped_id": ped_obj.entity_id, "matched_targetline": matched_result[0], "targetline_detail": matched_result[1] } return None # 仿真主循环调用示例 while simulation_is_running: # 替换为你获取所有PedSource生成行人的接口 all_pedestrians = ped_source.get_all_active_peds() for single_ped in all_pedestrians: ped_target_data = fetch_ped_current_target(single_ped) if ped_target_data: # 后续可以在这里做数据存储、逻辑触发等操作 print(f"行人{ped_target_data['ped_id']}当前行进目标:{ped_target_data['matched_targetline']}")
适配说明
- 代码中涉及仿真平台接口的部分,替换为你当前使用平台的对应方法即可,所有支持PedSource行人生成的主流仿真平台都开放了行人导航终点的读取接口
match_range参数可以根据场景内targetline的实际宽度调整,避免出现跨targetline的匹配错误- 逐帧运行该逻辑可以自动识别行人中途更换目的地的情况,实时返回最新的目标targetline信息
内容的提问来源于stack exchange,提问作者ruby zou
相关产品推荐
相关产品推荐

