navigation.gd 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. extends Node2D
  2. @export var character_speed: float = 400.0
  3. var path = []
  4. @onready var character = $Character
  5. #var navmap = NavigationServer2D.map_create()
  6. func _ready():
  7. pass
  8. #NavigationServer2D.region_set_map(navmap, $NavigationRegion2d.get_rid())
  9. func _process(delta):
  10. character.position = $NavigationAgent2d.get_next_location()
  11. var walk_distance = character_speed * delta
  12. #move_along_path(walk_distance)
  13. # The "click" event is a custom input action defined in
  14. # Project > Project Settings > Input Map tab.
  15. func _unhandled_input(event):
  16. if not event.is_action_pressed("click"):
  17. return
  18. _update_navigation_path(Vector2(), get_local_mouse_position())
  19. #func move_along_path(distance):
  20. # return
  21. # var last_point = character.position
  22. # while path.size():
  23. # var distance_between_points = last_point.distance_to(path[0])
  24. # # The position to move to falls between two points.
  25. # if distance <= distance_between_points:
  26. # character.position = last_point.lerp(path[0], distance / distance_between_points)
  27. # return
  28. # # The position is past the end of the segment.
  29. # distance -= distance_between_points
  30. # last_point = path[0]
  31. # path.remove(0)
  32. # # The character reached the end of the path.
  33. # character.position = last_point
  34. # set_process(false)
  35. var drawpos = Vector2()
  36. func _update_navigation_path(start_position, end_position):
  37. # get_simple_path is part of the Node2D class.
  38. # It returns a PackedVector2Array of points that lead you
  39. # from the start_position to the end_position.
  40. $NavigationAgent2d.set_target_location(end_position)
  41. drawpos = end_position
  42. queue_redraw()
  43. # The first point is always the start_position.
  44. # We don't need it in this example as it corresponds to the character's position.
  45. #path.remove(0)
  46. #set_process(true)
  47. func _draw():
  48. draw_circle(drawpos, 10, Color.RED)