Godot Version
4.4
Question
I want to use the NavigationServer2D to generate a path between two points on a TileMap with a navigation layer. The TileMap and active navigation with an agent is working properly.
The idea is to generate a path for a npc on Map X while the player is on Map Y.
I tried to load the map and get the NavigationRegion2D to have this as PathQueryParameters.map
but it doesnt generate a path, its empty.
Then i tried to load the Map X in a Subviewport to get the navigation map via temp_viewport.get_world_2d().navigation_map.
Also here i had no luck.
Is there a way?
I tried with both functions, “get_navigation_path” and “generate_path”.
var this_map
this_map = Utility.load_from_file(map_key_from_order, ".tscn", Directories.maps_scenes_dir)
var target_map_instance = this_map.instantiate()
var temp_viewport = SubViewport.new()
add_child(temp_viewport)
temp_viewport.world_2d = World2D.new()
temp_viewport.add_child(target_map_instance)
var target_navigation_map = temp_viewport.get_world_2d().navigation_map
print("TEMP VIEWPORT Navigationsmap: " + str(target_navigation_map))
## generate the current path
#npc.current_path = generate_path(target_navigation_map, start_location, end_location)
npc.current_path = get_navigation_path(target_navigation_map, start_location[0], end_location[0])
func get_navigation_path(target_navigation_map, p_start_position: Vector2, p_target_position: Vector2) -> PackedVector2Array:
if not is_inside_tree():
return PackedVector2Array()
var default_map_rid: RID = target_navigation_map
var path: PackedVector2Array = NavigationServer2D.map_get_path(
default_map_rid,
p_start_position,
p_target_position,
true,
31
)
print("this path: " + str(path))
return path
func generate_path(navigation_region, start_point, end_point):
if not navigation_region:
push_error("NavigationRegion2D or Path2D not assigned in Inspector!")
return
if start_point.is_empty() or end_point.is_empty():
push_error("No Start or Endpoint set")
return
# NavigationServer2D: Pfad berechnen
var PathQueryParameters = NavigationPathQueryParameters2D.new()
PathQueryParameters.start_position = start_point[0]
PathQueryParameters.target_position = end_point[0]
PathQueryParameters.map = navigation_region
var query_result = NavigationPathQueryResult2D.new()
NavigationServer2D.query_path(PathQueryParameters, query_result)
if query_result.path.size() == 0:
push_error("Path could not be generated")
return