navigation.gd 1.5 KB

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