character.gd 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. extends Marker3D
  2. @export var character_speed := 10.0
  3. @export var show_path := true
  4. var _nav_path_line: Line3D
  5. @onready var _nav_agent := $NavigationAgent3D as NavigationAgent3D
  6. func _ready() -> void:
  7. _nav_path_line = Line3D.new()
  8. add_child(_nav_path_line)
  9. _nav_path_line.set_as_top_level(true)
  10. func _physics_process(delta: float) -> void:
  11. if _nav_agent.is_navigation_finished():
  12. return
  13. var next_position := _nav_agent.get_next_path_position()
  14. var offset := next_position - global_position
  15. global_position = global_position.move_toward(next_position, delta * character_speed)
  16. # Make the robot look at the direction we're traveling.
  17. # Clamp Y to 0 so the robot only looks left and right, not up/down.
  18. offset.y = 0
  19. if not offset.is_zero_approx():
  20. look_at(global_position + offset, Vector3.UP)
  21. func set_target_position(target_position: Vector3) -> void:
  22. _nav_agent.set_target_position(target_position)
  23. # Get a full navigation path with the NavigationServer API.
  24. if show_path:
  25. var start_position := global_transform.origin
  26. var optimize := true
  27. var navigation_map := get_world_3d().get_navigation_map()
  28. var path := NavigationServer3D.map_get_path(
  29. navigation_map,
  30. start_position,
  31. target_position,
  32. optimize
  33. )
  34. _nav_path_line.draw_path(path)