character.gd 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. extends Marker3D
  2. const Line3D = preload("res://line3d.gd")
  3. @export var character_speed := 10.0
  4. @export var show_path := true
  5. @onready var _nav_agent := $NavigationAgent3D as NavigationAgent3D
  6. var _nav_path_line : Line3D
  7. func _ready():
  8. _nav_path_line = Line3D.new()
  9. add_child(_nav_path_line)
  10. _nav_path_line.set_as_top_level(true)
  11. func _physics_process(delta):
  12. if _nav_agent.is_navigation_finished():
  13. return
  14. var next_position := _nav_agent.get_next_path_position()
  15. var offset := next_position - global_position
  16. global_position = global_position.move_toward(next_position, delta * character_speed)
  17. # Make the robot look at the direction we're traveling.
  18. # Clamp y to 0 so the robot only looks left and right, not up/down.
  19. offset.y = 0
  20. look_at(global_position + offset, Vector3.UP)
  21. func set_target_position(target_position: Vector3):
  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. _nav_path_line.draw_path(path)