Random Navigable Point Within Distance

Godot Version

v4.7.1.stable.official [a13da4feb]

Question

How can I get a random point within a certain range of an NPC (CharacterBody2D) to set as a target for ‘wandering’ behavior? In the NPC’s code I have tried:

func _physics_process(delta:float) -> void:
	var nav:NavigationAgent2D = $NavigationAgent2D
	while to_local(nav.target_position).length() > npc_max_wander_distance:
		nav.target_position = NavigationServer2D.map_get_random_point(get_world_2d().get_navigation_map(),1,false)
		nav.get_next_path_position() # Updates navigation logic for next iteration. I tried it with this commented out as well.

But this just traps the game in an infinite loop. What can I do?

Use print statements to see what your code is doing and what are the values of relevant variables.