I'm trying to debug why avoidance doesn't seem to work with Godot's 2D navigation tutorial example code.
I've updated the example code to use
set_velocity(). This required changes
in two places. First, in _ready, I need
to hook up the velocity_computed
callback:
func _ready():
# This hooks up the computed velocity when avoidance is being used.
navigation_agent.velocity_computed.connect(update_movement)
# Omitted...Then, in _physics_process, I need to
call NavigationAgent2D's
set_velocity instead of
move_and_slide so that it can be used
in the collision avoidance algorithm.
func _physics_process(delta):
if navigation_agent.is_navigation_finished():
return
var current_agent_position: Vector2 = global_position
var next_path_position: Vector2 = navigation_agent.get_next_path_position()
var new_velocity: Vector2 = next_path_position - current_agent_position
new_velocity = new_velocity.normalized()
new_velocity = new_velocity * movement_speed
# Tell the navigation agent about the desired velocity
navigation_agent.set_velocity(new_velocity)
func update_movement(new_velocity: Vector2) -> void:
velocity = new_velocity
move_and_slide()After the collision avoidance has been computed,
the new velocity is sent to
update_movement via the
velocity_computed signal that was set
up earlier at the end of
_physics_processand we can move
correctly using the new velocity.
Important things I noticed:
- The
max_speedproperty will clamp the magnitude of the velocity passed toset_velocityto themax_speedvalue.