navigation.gd 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. extends Navigation2D
  2. export(float) var CHARACTER_SPEED = 400.0
  3. var path = []
  4. # The 'click' event is a custom input action defined in
  5. # Project > Project Settings > Input Map tab
  6. func _input(event):
  7. if not event.is_action_pressed('click'):
  8. return
  9. _update_navigation_path($Character.position, get_local_mouse_position())
  10. func _update_navigation_path(start_position, end_position):
  11. # get_simple_path is part of the Navigation2D class
  12. # it returns a PoolVector2Array of points that lead you from the
  13. # start_position to the end_position
  14. path = get_simple_path(start_position, end_position, true)
  15. # The first point is always the start_position
  16. # We don't need it in this example as it corresponds to the character's position
  17. path.remove(0)
  18. set_process(true)
  19. func _process(delta):
  20. var walk_distance = CHARACTER_SPEED * delta
  21. move_along_path(walk_distance)
  22. func move_along_path(distance):
  23. var last_point = $Character.position
  24. for index in range(path.size()):
  25. var distance_between_points = last_point.distance_to(path[0])
  26. # the position to move to falls between two points
  27. if distance <= distance_between_points and distance >= 0.0:
  28. $Character.position = last_point.linear_interpolate(path[0], distance / distance_between_points)
  29. break
  30. # the character reached the end of the path
  31. elif distance < 0.0:
  32. $Character.position = path[0]
  33. set_process(false)
  34. break
  35. distance -= distance_between_points
  36. last_point = path[0]
  37. path.remove(0)